define(['jquery', 'domReady!', 'appLocalStorage', 'appConst',
        'model/global', 'model/grrData', 'business/searchbar/searchbarBiz',
        'stringUtils', 'model/project', 'common/widgetUtils', 'common/mathUtils', 'model/export', 'appMessageBox', 'business/analysis/grr/grrConfig', 'dateUtils', 'business/socket/socketBiz', 'd3/d3-main', 'x-editable/x-editable.min', 'jquery-form/jquery-form.min', 'jeditable/jquery.jeditable'],
    function ($, domReady, appLocalStorage, appConst, global, grrM, searchbar, stringUtils, projectM, widgetUtils, mathUtils, chartExportM, msgBox, grrConfig, dateUtils, socketBiz) {
        var components = {};
        var data = {
            searchFields: {},
            projectDS: [],
            psGrrDataDS: {},
            grrSettingDS: {},
            grrItemDataDS: [],
            grrSummaryDS: [],
            grrSummarySlotDS: [],
            grrItemDetailDS: [],
            grrSummaryAnovaDS: [],
            grrSummarySourceDS: [],
            grrViewDataDS: [],
            grrChoiceTestItemDS: [],
            grrChartDS: {},
            grrExportTestItemDS: [],
            psGrrData: [],

            importPsGrrDataDS: {},
            importPsaDs: [],
            currentImportProjectModel: "NORMAL",
            currentGrrName: "",
            currentTabName: "tab_analysis",
            currentSelectedGroupKey: "",
            currentGroupKey: "",
            currentItemName: "",
            custom: {
                digit: 4,
                search_timeout_key_grr: ""
            },
            grrExportcheckValues: [],
            ws: {
                sockjs: null,
                stomp: null
            }
        };
        var that;

        function checkSummaryLevel(s) {
            if ("EXCELLENT" == s) {
                return {name: "Excellent", value: "success"};
            } else if ("GOOD" == s) {
                return {name: "Adequate", value: "info"};
            } else if ("ACCEPTABLE" == s) {
                return {name: "Marginal", value: "warning"};
            } else if ("RECTIFICATION" == s) {
                return {name: "Bad", value: "danger"};
            }
        }

        function splitSlotName(s) {
            var stationId = s.substring(0, s.lastIndexOf('_'));
            var result = {stationId: stationId, slotNos: []};
            var slotId = s.substring(s.lastIndexOf('_') + 1, s.length);
            if (slotId.indexOf(",") != -1) {
                var slotIds = slotId.split(",");
                if (slotIds != null && slotIds.length > 0) {
                    $.each(slotIds, function (i, slot) {
                        result.slotNos.push(slot);
                    });
                }
                return result;
            } else {
                return {stationId: stationId, slotNos: [slotId]};
            }
        }

        return {
            init: function () {
                that = this;
                data.search_timeout_key_grr = appConst.searchKey.search_dataImport_timeout_key + "grr." + global.getUserId();
                components = {
                    wgt_grrSummary: $('#wgt_grrSummary'),
                    tab_pageTab: $('#tab_pageTab'),

                    btn_grr_deleteGrrItem: $('#btn_grr_deleteGrrItem'),
                    tbl_grr_itemData: $('#tbl_grr_itemData'),
                    txt_grr_itemDataFilter: $('#txt_grr_itemDataFilter'),
                    lbl_grr_setting: {
                        appraisers: $('#spn_grr_setting_a'),
                        trials: $('#spn_grr_setting_t'),
                        parts: $('#spn_grr_setting_p')
                    },
                    lbl_grr_psSetting: {
                        bad: $('#spn_grr_psattr_bad'),
                        marginal: $('#spn_grr_psattr_marginal'),
                        adequate: $('#spn_grr_psattr_adequate'),
                        excellent: $('#spn_grr_psattr_excellent')
                    },

                    spn_grr_detail_title: $('#spn_grr_detail_title'),
                    tbl_grr_summary: $('#tbl_grr_summary'),
                    tbl_grr_itemDetail: $('#tbl_grr_itemDetail'),
                    tbl_grr_anova: $('#tbl_grr_anova'),
                    tbl_grr_source: $('#tbl_grr_source'),
                    slt_grr_summary_slot: $('#slt_grr_summary_slot'),
                    div_grr_summary_bar: $('#div_grr_summary_bar'),
                    btn_grr_collapseBtn1: $('#btn_grr_collapseBtn1'),
                    btn_grr_collapseBtn2: $('#btn_grr_collapseBtn2'),
                    btn_grr_collapseBtn3: $('#btn_grr_collapseBtn3'),
                    spn_grr_detail_itemname: $('#spn_grr_detail_itemname'),
                    spn_grr_detail_tolerance: $('#spn_grr_detail_tolerance'),
                    cht_grr_xbar: $('#cht_grr_xbar'),
                    cht_grr_r: $('#cht_grr_r'),
                    cht_grr_resbyoperator: $('#cht_grr_resbyoperator'),
                    cht_grr_resbypart: $('#cht_grr_resbypart'),
                    cht_grr_components: $('#cht_grr_components'),
                    cht_grr_plot: $('#cht_grr_plot'),
                    spn_grr_source_sigma: $('#spn_grr_source_sigma'),
                    a_grr_source_sigma: $('#a_grr_source_sigma'),

                    slt_grr_viewdata_slot: $('#slt_grr_viewdata_slot'),
                    tbl_grr_viewdata: $('#tbl_grr_viewdata'),
                    btn_grr_viewdata_submit: $('#btn_grr_viewdata_submit'),
                    btn_grr_viewdata_choiceitem: $('#btn_grr_viewdata_choiceitem'),

                    slt_grr_import_project: $('#slt_grr_import_project'),
                    alt_grr_import_msgbar: $('#alt_grr_import_msgbar'),
                    fle_grr_import_file: $('#fle_grr_import_file'),
                    fle_grr_import_file2: $('#fle_grr_import_file2'),
                    btn_grr_import: $('#btn_grr_import'),
                    dlg_grr_import: $('#dlg_grr_import'),
                    wzd_grr_import: $('#wzd_grr_import').wizard(),
                    frm_grr_import: $('#frm_grr_import'),
                    frm_grr_import2: $('#frm_grr_import2'),
                    // var wizard = components.wzd_grr_import.wizard();
                    slt_grr_import_type: $('#slt_grr_import_type'),
                    slt_grr_import_firstChange: $('#slt_grr_import_firstChange'),
                    txt_grr_import_operatorValue: $('#txt_grr_import_operatorValue'),
                    txt_grr_import_trialValue: $('#txt_grr_import_trialValue'),
                    txt_grr_import_partValue: $('#txt_grr_import_partValue'),
                    btn_grr_import_submit: $('#btn_grr_import_submit'),
                    btn_grr_import_gobackTo1: $('#btn_grr_import_gobackTo1'),
                    txt_grr_import_projectId: $('#txt_grr_import_projectId'),
                    txt_grr_import_grrName: $('#txt_grr_import_grrName'),

                    slt_grr_import_type2: $('#slt_grr_import_type2'),
                    txt_grr_import_operatorValue2: $('#txt_grr_import_operatorValue2'),
                    txt_grr_import_trialValue2: $('#txt_grr_import_trialValue2'),
                    txt_grr_import_partValue2: $('#txt_grr_import_partValue2'),
                    slt_grr_import_slotGroup: $('#slt_grr_import_slotGroup'),
                    txt_grr_import_projectId2: $('#txt_grr_import_projectId2'),
                    txt_grr_import_grrName2: $('#txt_grr_import_grrName2'),

                    spn_grr_import_time: $('#spn_grr_import_time'),
                    spn_grr_import_processbar: $('#spn_grr_import_processbar'),
                    spn_grr_import_status: $('#spn_grr_import_status'),
                    spn_grr_import_logArea: $('#spn_grr_import_logArea'),
                    txt_grr_import_soltkey: $('#txt_grr_import_soltkey'),
                    txt_grr_import_soltkey2: $('#txt_grr_import_soltkey2'),
                    spn_grr_import_operator: $('#spn_grr_import_operator'),
                    slt_grr_import_bind_group_f: $('#slt_grr_import_bind_group_f'),
                    slt_grr_import_bind_group_s: $('#slt_grr_import_bind_group_s'),
                    slt_grr_import_bind_attr_part: $('#slt_grr_import_bind_attr_part'),
                    slt_grr_import_bind_group_f2: $('#slt_grr_import_bind_group_f2'),
                    slt_grr_import_bind_group_s2: $('#slt_grr_import_bind_group_s2'),
                    slt_grr_import_bind_attr_part2: $('#slt_grr_import_bind_attr_part2'),
                    slt_grr_import_bind_attr_operator: $('#slt_grr_import_bind_attr_operator'),

                    slt_grr_import_bind_group_f_isdefualt: $('#slt_grr_import_bind_group_f_isdefualt'),
                    slt_grr_import_bind_group_s_isdefualt: $('#slt_grr_import_bind_group_s_isdefualt'),
                    slt_grr_import_bind_attr_part_isdefualt: $('#slt_grr_import_bind_attr_part_isdefualt'),
                    slt_grr_import_bind_group_f2_isdefualt: $('#slt_grr_import_bind_group_f2_isdefualt'),
                    slt_grr_import_bind_group_s2_isdefualt: $('#slt_grr_import_bind_group_s2_isdefualt'),
                    slt_grr_import_bind_attr_part2_isdefualt: $('#slt_grr_import_bind_attr_part2_isdefualt'),
                    slt_grr_import_bind_attr_operator_isdefualt: $('#slt_grr_import_bind_attr_operator_isdefualt'),

                    btn_grr_export: $("#btn_grr_export"),
                    dlg_grr_export: $("#dlg_grr_export"),
                    tbl_grr_export_testItem: $("#tbl_grr_export_testItem"),
                    ckb_grr_export_allCheck: $("#ckb_grr_export_allCheck"),
                    btn_grr_export_submit: $("#btn_grr_export_submit"),
                    radio_grr_export_type: $("input[name='grr_export_type']"),

                    dlg_grr_choice: $('#dlg_grr_choice'),
                    tbl_grr_choice_testitem: $('#tbl_grr_choice_testitem'),
                    ckb_grr_choice_testitem_topAll: $('#ckb_grr_choice_testitem_topAll'),
                    btn_grr_choice_submit: $('#btn_grr_choice_submit')
                };


                grrConfig.init();


                that.initGrrItemPanel();
                that.initCenterPanel();
            },
            searchEventListener: function (searchFields) {
                data.searchFields = searchFields;
                that.loadPsGrrData(searchFields, function (d) {
                    data.psGrrDataDS = d;
                });
                that.loadGrrItemTable();
                that.cleanPanel();
                that.resetAllPanel();
            },

            initPageTab: function () {
                components.tab_pageTab.on('shown.bs.tab', function (e) {
                    data.currentTabName = $(this).find('li.active > a').attr('id');
                    if (stringUtils.isBlank(data.currentGrrName)) {
                        return false;
                    }
                    that.setSlotValue();
                    that.loadData();
                });
            },
            cleanPanel: function () {
                that.cleanAnalysisPanel();
                that.cleanViewDataTable();
            },
            loadData: function () {
                if (data.currentTabName == 'tab_analysis') {
                    data.grrChoiceTestItemDS = [];
                    data.grrExportTestItemDS = [];
                    that.toggleAnovaAndSourceSubPanel('hide');
                    that.setAnalysisPanel();
                    that.loadSummaryTable();
                } else if (data.currentTabName == 'tab_viewData') {
                    data.grrChoiceTestItemDS = [];
                    data.grrExportTestItemDS = [];
                    that.loadViewDataTable();
                    that.setAnalysisPanel();
                }
            },
            setSlotValue: function () {
                if (data.currentSelectedGroupKey != "") {
                    components.slt_grr_summary_slot.select2('val', data.currentSelectedGroupKey);
                    components.slt_grr_viewdata_slot.select2('val', data.currentSelectedGroupKey);
                } else {
                    if (data.grrSummarySlotDS.length != 0) {
                        components.slt_grr_summary_slot.select2('val', data.grrSummarySlotDS[0].id);
                        components.slt_grr_viewdata_slot.select2('val', data.grrSummarySlotDS[0].id);
                        data.currentSelectedGroupKey = data.grrSummarySlotDS[0].id;
                        data.currentGroupKey = data.grrSummarySlotDS[0].odata;
                    } else {
                        data.currentSelectedGroupKey = "";
                        data.currentGroupKey = "";
                    }
                }
            },
            loadPsGrrData: function (param, callback) {
                grrM.findPSInfo(param, function (d) {
                    if ($.isFunction(callback)) {
                        callback(d);
                    }
                });
            },
            initGrrItemPanel: function () {
                that.initGrrItemTable();
                that.initGrrItemFilter();

                components.btn_grr_deleteGrrItem.on('click', function (e) {
                    var param = {
                        search_projectId: data.searchFields.search_projectId,
                        search_grrName: data.currentGrrName
                    };
                    msgBox.show({
                        content: "Are you sure to delete this GRR Data[" + data.currentGrrName + "]? <p class='text-align-right'>" +
                        "<button type='submit' class='btn btn-primary btn-sm deleteGrrItem'>" + $.i18n.prop("GLOBAL_BUTTON_YES") + "</button> " +
                        "<a href='javascript:void(0);' class='btn btn-danger btn-sm'>" + $.i18n.prop("GLOBAL_BUTTON_NO") + "</a></p>",
                        type: 'normal'
                    });
                    $("#divSmallBoxes").find(".deleteGrrItem").unbind('click').on('click', function (data) {
                        grrM.deleteGrrItem(param, function (d) {
                            msgBox.successBox();
                            that.cleanPanel();
                            that.resetAllPanel();
                            that.loadGrrItemTable();
                        });
                    });
                });
            },
            initGrrItemTable: function () {
                data.grrItemDataDS = [];
                var tb = components.tbl_grr_itemData;
                tb.dataTable({
                    "sDom": "rt",
                    "processing": true,
                    "ordering": false,
                    "paging": false,
                    "lengthChange": false,
                    "searching": true,
                    "bFilter": false,
                    "autoWidth": true,
                    "data": function () {
                        return data.grrItemDataDS;
                    },
                    "language": appConst.table_language(),
                    "columnDefs": [
                        {
                            "targets": [0],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).attr('style', 'cursor:pointer;');
                            }
                        }
                    ]
                });
                tb.find("thead").hide();

                tb.find('tbody').on('click', 'tr', function () {
                    if ($(this).hasClass('active')) {
                        // $(this).removeClass('active');
                        return;
                    } else {
                        tb.DataTable().$('tr.active').removeClass('active');
                        $(this).addClass('active');
                    }
                    data.currentGrrName = tb.DataTable().row(this).data()[0];
                    components.btn_grr_deleteGrrItem.prop("disabled", false);
                    that.loadGrrSettings(function () {

                        that.loadSummarySlot(function () {
                            data.currentSelectedGroupKey = "";
                            that.setSlotValue();
                            // that.loadSummaryTable();
                            components.btn_grr_export.prop("disabled", false);
                            components.btn_grr_viewdata_submit.prop("disabled", false);
                            components.btn_grr_viewdata_choiceitem.prop("disabled", false);
                            that.loadData();
                        });

                    });
                });
            },
            initGrrItemFilter: function () {
                components.txt_grr_itemDataFilter.on('keyup', function (e) {
                    var text = components.txt_grr_itemDataFilter.val();
                    that.doFilterGrrItem(text);
                });
            },
            loadGrrItemTable: function () {
                data.currentGrrName = "";
                components.txt_grr_itemDataFilter.val("");
                grrM.findGrrItem(data.searchFields, function (d) {
                    data.grrItemDataDS = [];
                    // data.grrItemDataDS = d;
                    $.each(d, function (i, obj) {
                        data.grrItemDataDS.push([obj]);
                    });
                    components.tbl_grr_itemData.dataTable().api().clear().column(0).search("");
                    components.tbl_grr_itemData.dataTable().api().rows.add(data.grrItemDataDS).draw();
                });
            },
            doFilterGrrItem: function (param) {
                components.tbl_grr_itemData.dataTable().api().column(0).search(param).draw();
            },
            initCenterPanel: function () {
                that.initPageTab();

                that.initSummaryPanel();
                that.initViewDataPanel();
            },

            //Summary Panel
            initSummaryPanel: function () {
                that.initSummarySlot();
                that.initSummaryPanelCols();
                that.initGrrSummaryTable();

                that.initSummaryAnovaTable();
                that.initSummarySourceTable();
                that.toggleAnovaAndSourceSubPanel('hide');

                that.initGrrImportModalDialog();

                that.initGrrExportModalDialog();
            },
            loadGrrSettings: function (callback) {
                var param = {
                    search_projectId: data.searchFields.search_projectId,
                    search_grrName: data.currentGrrName
                };

                grrM.findSetting(param, function (d) {
                    data.grrSettingDS = d;
                    if ($.isFunction(callback)) {
                        callback();
                    }
                });
            },
            setAnalysisPanel: function () {
                that.setAnalysisPanelTopBar();
            },
            setAnalysisPanelTopBar: function () {
                var rule = JSON.parse(data.psGrrDataDS.rule);
                components.lbl_grr_psSetting.bad.html(rule[2]);
                components.lbl_grr_psSetting.marginal.html(rule[2]);
                components.lbl_grr_psSetting.adequate.html(rule[1]);
                components.lbl_grr_psSetting.excellent.html(rule[0]);

                components.lbl_grr_setting.appraisers.html("<strong>" + data.grrSettingDS.operatorValue + "</strong>");
                components.lbl_grr_setting.parts.html("<strong>" + data.grrSettingDS.partValue + "</strong>");
                components.lbl_grr_setting.trials.html("<strong>" + data.grrSettingDS.trialValue + "</strong>");
                components.div_grr_summary_bar.show();

            },
            cleanAnalysisPanelTopBar: function () {
                components.lbl_grr_psSetting.bad.empty();
                components.lbl_grr_psSetting.marginal.empty();
                components.lbl_grr_psSetting.adequate.empty();
                components.lbl_grr_psSetting.excellent.empty();

                components.lbl_grr_setting.appraisers.empty();
                components.lbl_grr_setting.parts.empty();
                components.lbl_grr_setting.trials.empty();
                components.div_grr_summary_bar.hide();
            },
            cleanAnalysisPanel: function () {
                that.cleanAnalysisPanelTopBar();
                that.cleanSummaryTable();
                that.cleanDetailTable();
            },

            initSummarySlot: function () {
                data.grrSummarySlotDS = [];
                data.currentGroupKey = "";
                components.slt_grr_summary_slot.select2({
                    id: function (rs) {
                        return rs.id;
                    },
                    allowClear: false,
                    data: function () {
                        return {results: data.grrSummarySlotDS};
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.text == null ? '' : d.text + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.text == null ? '' : d.text;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_summary_slot.on('change', function (e) {
                    data.currentSelectedGroupKey = $(this).select2('val');
                    data.currentGroupKey = $(this).select2('data').odata;
                    that.loadSummaryTable();
                });
            },
            loadSummarySlot: function (callback) {
                var param = {
                    search_projectId: data.searchFields.search_projectId,
                    search_grrName: data.currentGrrName
                };
                grrM.findSlot(param, function (d) {
                    var arr = [];
                    $.each(d, function (i, obj) {
                        var groupkey = obj.groupKey;
                        var dimensionList = obj.dimensionList;

                        if (dimensionList != null && dimensionList.length > 0) {
                            $.each(dimensionList, function (i1, dobj) {
                                var ddobj = dobj.split(',');
                                var array = [];

                                for (var i = 0; i < ddobj.length; i++) {
                                    array.push(ddobj[i]);
                                }

                                var object = $.extend({}, obj);
                                object.dimensionList = array;
                                arr.push({
                                    odata: object,
                                    id: groupkey + "_" + dobj,
                                    text: groupkey == "" ? (dobj == "" ? "" : dobj) : groupkey.replace(' @#! ', '_') + (dobj == "" ? "" : ("_" + dobj))
                                });
                            });
                        } else {
                            arr.push({
                                odata: obj,
                                id: groupkey,
                                text: groupkey.replace(' @#! ', '_')
                            });
                        }
                    });
                    data.grrSummarySlotDS = arr;
                    if ($.isFunction(callback)) {
                        callback();
                    }
                });
            },
            initGrrSummaryTable: function () {
                data.grrSummaryDS = [];
                var tb = components.tbl_grr_summary;
                tb.dataTable({
                    // "sDom": "rt",
                    "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                    "processing": true,
                    "ordering": false,
                    "paging": true,
                    "lengthChange": false,
                    "searching": true,
                    "bFilter": false,
                    "autoWidth": true,
                    "pageLength": global.getPageSize(),
                    "data": function () {
                        return data.grrSummaryDS;
                    },
                    "language": appConst.table_language(),
                    "columnDefs": [
                        {
                            "targets": [1],
                            "render": function (d, type, full) {
                                if (d == null) {
                                    return "";
                                }
                                return type === 'display' && d.length > 20 ?
                                '<span title="' + d + '">' + d.substr(0, 17) + '...</span>' :
                                    d;
                            }
                        },
                        {
                            "targets": [2],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('data-code', cellData);
                            },
                            "render": function (d, type, full) {
                                if (mathUtils.isNaN(d)) {
                                    return "-";
                                } else {
                                    return mathUtils.round(d, 4);
                                }
                                return d;
                            }
                        },
                        {
                            "targets": [3],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                $(td).addClass('inputTd').attr('data-code', cellData);
                            },
                            "render": function (d, type, full) {
                                if (mathUtils.isNaN(d)) {
                                    return "-";
                                } else {
                                    return mathUtils.round(d, 4);
                                }
                                return d;
                            }
                        },
                        {
                            "targets": [4],
                            "render": function (d, type, full) {
                                if (mathUtils.isNaN(d)) {
                                    return "-";
                                } else {
                                    return mathUtils.round(d, data.custom.digit);
                                }
                                return d;
                            }
                        },
                        {
                            "targets": [5],
                            "render": function (d, type, full) {
                                // if (d != "-" && d != 'NaN') {
                                //     return mathUtils.round(d, 2) + "%";
                                // }
                                if (mathUtils.isNaN(d)) {
                                    return "-";
                                } else {
                                    return mathUtils.round(d, 2) + "%";
                                }
                                return d;
                            }
                        },
                        {
                            "targets": [6],
                            "render": function (d, type, full) {
                                if (mathUtils.isNaN(d)) {
                                    return "-";
                                } else {
                                    return mathUtils.round(d, 2) + "%";
                                }
                                return d;
                            }
                        },
                        {
                            "targets": [7],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                var result = checkSummaryLevel(rowData[8]);
                                $(td).addClass(result.value);
                            },
                            "render": function (d, type, full) {
                                if (mathUtils.isNaN(d)) {
                                    return "-";
                                } else {
                                    return '<a href="javascript:void(0);" class="grrLink" data-code="' + full[1] + '" data-tolerance-code="' + full[4] + '" data-sl="[' + full[3] + ', ' + full[2] + ']" data-cache=' + full[9] + '>' + mathUtils.round(d, 2) + '%</a>';
                                }
                                return d;
                            }
                        },
                        {
                            "targets": [8],
                            "createdCell": function (td, cellData, rowData, row, col) {
                                var result = checkSummaryLevel(cellData);
                                $(td).addClass(result.value).html(result.name);
                            },
                            "searchable": false
                        }
                    ],
                    "drawCallback": function (settings) {
                        var api = this.api();
                        tb.find('tbody td.inputTd').jeditable(function (value, settings) {
                            var cell = api.cell(this);
                            var cellOldValue = mathUtils.isNaN(cell.data()) ? '-' : mathUtils.round(cell.data(), data.custom.digit);

                            cell.data(value);
                            var cellIndex = cell.index();

                            var rowData = api.row(cellIndex.row).data();
                            var lsl = rowData[2];
                            var usl = rowData[3];

                            if (value == '-' || value == '' || mathUtils.isNaN(value)) {
                                if (!mathUtils.isNaN(cellOldValue)) {
                                    if (Number(usl) <= Number(lsl)) {
                                        $(this).addClass("errorcell");
                                        return false;
                                    }
                                    $(this).removeClass("errorcell");
                                    cell.data(cellOldValue);
                                }
                                return cellOldValue;
                            }

                            if (mathUtils.isNaN(lsl) || mathUtils.isNaN(usl)) {
                                return;
                            }

                            if (Number(usl) <= Number(lsl)) {
                                // $(api.cell(cellIndex.row, 7).node()).attr('class', result.value);
                                $(this).addClass("errorcell");
                                return false;
                            } else {
                                $(this).removeClass("errorcell");
                            }
                            var param = that.getSearchParams();
                            param.search_LSL = rowData[2];
                            param.search_USL = rowData[3];
                            param.search_itemName = rowData[1];

                            grrM.refreshGrrSummary(param, function (d) {
                                var arr = new Array();
                                arr.push(null);
                                arr.push(d.itemName);
                                arr.push(d.lsl);
                                arr.push(d.usl);
                                arr.push(d.tolerance);
                                arr.push(d.partVariation);
                                arr.push(d.totalProcessVariation);
                                arr.push(d.grr);

                                var result = checkSummaryLevel(d.result);
                                arr.push(result.name);
                                arr.push(true);

                                api.row(cellIndex.row).data(arr).draw();
                                $(api.cell(cellIndex.row, 7).node()).attr('class', result.value);
                                $(api.cell(cellIndex.row, 8).node()).attr('class', result.value);

                                if (data.currentItemName == rowData[1]) {
                                    $(api.cell(cellIndex.row, 7).node()).find('a').trigger('click');
                                }
                            }, function () {

                            });
                        }, {
                            height: '20',
                            width: '100',
                            //onblur:'ignore',
                            cssclass: 'smart-form',
                            placeholder: "Invalidate Value"
                        });
                    }
                });
                tb.DataTable().on('draw.dt', function () {
                    tb.api().column(0, {draw: 'applied'}).nodes().each(function (cell, i) {
                        cell.innerHTML = i + 1;
                    });

                    var sigma = data.psGrrDataDS.sigma;
                    components.a_grr_source_sigma.attr('data-value', sigma);
                    components.a_grr_source_sigma.editable({
                        source: function () {
                            return [{id: "6.0", text: "6.0"}, {id: "5.15", text: "5.15"}];
                        },
                        select2: {
                            width: 100
                        }
                    });

                    tb.find('tbody').find('.grrLink').unbind('click').on('click', function (e) {
                        tb.find('tbody > tr').removeClass('active');
                        var cell = tb.api().cell($(this).parent('td'));
                        $(tb.api().row(cell.index().row).node()).attr('class', 'active');

                        var itemName = $(this).attr('data-code');
                        var tolerance = $(this).attr('data-tolerance-code');
                        var ls = $(this).attr('data-sl');
                        var isCache = $(this).attr('data-cache');
                        // var sigma = data.psGrrDataDS.sigma;
                        data.currentItemName = itemName;

                        components.spn_grr_detail_itemname.html('<strong>' + itemName + '</strong>');
                        components.spn_grr_detail_tolerance.html('<strong>' + mathUtils.round(tolerance, data.custom.digit) + '</strong>');
                        var u = eval("(" + ls + ")");

                        components.spn_grr_detail_title.html("USL: " + u[0] + ", LSL: " + u[1]);
                        components.spn_grr_source_sigma.html(sigma);
                        components.a_grr_source_sigma.html(sigma);

                        components.a_grr_source_sigma.editable('setValue', sigma, sigma);
                        components.a_grr_source_sigma.editable('option', 'display', function (value) {
                            $(this).html(value);
                            var param = that.getSearchParams();
                            param = $.extend({}, param, {
                                search_itemName: itemName,
                                search_grrName: data.currentGrrName,
                                search_USL: u[0],
                                search_LSL: u[1],
                                search_sigmaParam: value,
                                isCache: true
                            });


                            widgetUtils.toggleWidgetLoading(components.wgt_grrSummary);
                            that.loadAnovaAndSource(param, function (d) {
                                that.loadSummarySourceTable();
                                grrM.findChartData(param, function (d) {
                                    data.grrChartDS = d;
                                    that.buildComponentsChart();
                                    widgetUtils.toggleWidgetLoading(components.wgt_grrSummary);
                                });
                            });
                        });
                        var param = {};
                        param.search_itemName = itemName;
                        if (isCache == 'true') {
                            param.isCache = true;
                            param.search_USL = u[0];
                            param.search_LSL = u[1];
                        }
                        widgetUtils.toggleWidgetLoading(components.wgt_grrSummary);
                        that.loadAnovaAndSource(param, function () {
                            that.buildSummaryItemDetailTable();
                            that.loadSummaryAnovaTable();
                            that.loadSummarySourceTable();
                            that.toggleAnovaAndSourceSubPanel('show');

                            that.loadChartData(function () {
                                that.buildCharts();

                            });
                            widgetUtils.toggleWidgetLoading(components.wgt_grrSummary);
                        });
                    });
                });
            },
            loadSummaryTable: function (d) {
                data.grrSummaryDS = [];
                var param = that.getSearchParams();
                // components.tbl_grr_summary.dataTable().api().clear().rows.add(data.grrSummaryDS).draw();
                widgetUtils.toggleWidgetLoading(components.wgt_grrSummary);
                grrM.findSummary(param, function (d) {
                    var dsArray = new Array();
                    $(d).each(function (i, obj) {
                        var arr = new Array();
                        arr.push(null);
                        arr.push(obj.itemName);
                        arr.push(obj.lsl);
                        arr.push(obj.usl);
                        arr.push(obj.tolerance);
                        arr.push(obj.partVariation);
                        arr.push(obj.totalProcessVariation);
                        arr.push(obj.grr);
                        arr.push(obj.result);
                        arr.push(false);
                        dsArray.push(arr);
                    });
                    data.grrSummaryDS = dsArray;
                    components.tbl_grr_summary.dataTable().api().clear().rows.add(data.grrSummaryDS).draw();
                    widgetUtils.toggleWidgetLoading(components.wgt_grrSummary);
                }, function () {
                    widgetUtils.toggleWidgetLoading(components.wgt_grrSummary, "reset");
                });
            },
            cleanSummaryTable: function () {
                components.tbl_grr_summary.dataTable().api().clear().draw();
            },
            cleanDetailTable: function () {
                components.tbl_grr_anova.dataTable().api().clear().draw();
                components.tbl_grr_source.dataTable().api().clear().draw();
                components.tbl_grr_itemDetail.empty();

                components.spn_grr_detail_itemname.html('-');
                components.spn_grr_detail_tolerance.html('-');
                components.spn_grr_detail_title.html('USL: -, LSL: -');
                that.toggleAnovaAndSourceSubPanel('hide');
            },

            initSummaryPanelCols: function () {
                $('.collapseBtn').on('click', function (e) {
                    var theOthers = $(this).parent().nextAll("div, ul, table, hr");
                    var img = $(this).find('span > i');
                    theOthers.toggle();

                    if (theOthers.is(":hidden")) {
                        img.removeClass('fa-angle-down');
                        img.addClass('fa-angle-left');
                    } else {
                        img.removeClass('fa-angle-left');
                        img.addClass('fa-angle-down');
                    }
                });
            },
            loadAnovaAndSource: function (param, callback) {
                data.grrItemDetailDS = [];
                var searchParam = that.getSearchParams();
                $.extend(searchParam, param);
                searchParam.search_itemName = param.search_itemName;
                searchParam.search_grrName = data.currentGrrName;

                if (param.isCache) {
                    grrM.refreshAnovaAndSource(searchParam, function (d) {
                        data.grrItemDetailDS = d;
                        if ($.isFunction(callback)) {
                            callback(d);
                        }
                    }, function () {
                        widgetUtils.toggleWidgetLoading(components.wgt_grrSummary, "reset");
                    });
                } else {
                    grrM.findAnovaAndSource(searchParam, function (d) {

                        data.grrItemDetailDS = d;
                        if ($.isFunction(callback)) {
                            callback(d);
                        }
                    }, function () {
                        widgetUtils.toggleWidgetLoading(components.wgt_grrSummary, "reset");
                    });
                }
            },
            buildSummaryItemDetailTable: function () {
                var digit = data.custom.digit;
                var isSlotModel = data.psGrrDataDS.model == "SLOT" ? true : false;

                //build item detail table
                var itemBody = components.tbl_grr_itemDetail;
                itemBody.empty('');
                var items = data.grrItemDetailDS.grrDataDtoList;
                var sLists = data.grrItemDetailDS.grrStatisticDataDtoList;
                if (items.length == 0) {
                    return false;
                }
                var cells = items[0].colValueDtoList;
                var tv = '<table class="table  table-bordered table-hover has-tickbox" style="margin-top: 0px !important;" width="100%"><thead>';
                var head = '<tr><th style="width:14%;">Operator</th> <th>Trial</th>';
                $.each(cells, function (index, obj) {
                    head += "<th>" + obj.key + "</th>";
                });
                head += "</tr>";
                tv += head + '</thead><tbody>';

                var operator = "";
                var meanIndex = 0;
                var roundIndex = 0;
                var staticIndex = Number(data.grrSettingDS.trialValue) - 1;

                $.each(items, function (i, obj) {

                    if (obj.operator != null) {
                        var op = obj.operator.length > 20 ?
                        '<span title="' + obj.operator + '">' + obj.operator.substr(0, 17) + '...</span>' :
                            obj.operator;
                    }
                    if (obj.trial != null) {
                        var tr = obj.trial.length > 8 ?
                        '<span title="' + obj.trial + '">' + obj.trial.substr(0, 5) + '...</span>' :
                            obj.trial;
                    }


                    tv += "<tr><td>" + op + "</td><td>" + tr + "</td>";

                    var cells = obj.colValueDtoList;
                    $.each(cells, function (i1, obj1) {
                        tv += "<td>" + mathUtils.round(obj1.value, digit) + "</td>";
                    });
                    tv += "</tr>";

                    var showHeadIndex = i + 1;
                    // var step = k % data.grrSettingDS.trialValue;
                    if (roundIndex == staticIndex) {
                        var sobj = sLists[meanIndex];

                        tv += "<tr class='foot-info'><td>AVG=" + mathUtils.round(sobj.mean, digit) + "</td><td>Mean</td>";
                        $.each(sobj.meanList, function (i1, obj1) {
                            tv += "<td>" + mathUtils.round(obj1.value, digit) + "</td>";
                        });
                        tv += "</tr>";

                        tv += "<tr class='foot-info'><td>Σ=" + mathUtils.round(sobj.rang, digit) + "</td><td>Range</td>";
                        $.each(sobj.rangList, function (i1, obj1) {
                            tv += "<td>" + mathUtils.round(obj1.value, digit) + "</td>";
                        });
                        tv += "</tr>";
                        if (showHeadIndex != data.grrSettingDS.operatorValue * data.grrSettingDS.trialValue) {
                            tv += head;
                        }
                        meanIndex++;
                        roundIndex = 0;
                    } else {
                        roundIndex++;
                    }

                    // if (i > 1 && step == 0) {
                    //
                    // }

                    // operator = obj.operator;
                });

                var sobj = sLists[sLists.length - 1];
                tv += "<tr class='foot'><td></td><td>Mean</td>";
                $.each(sobj.totalMeanList, function (i1, obj1) {
                    tv += "<td>" + mathUtils.round(obj1.value, digit) + "</td>";
                });
                tv += "</tr>";

                // sobj = sLists[sLists.length - 1];
                tv += "<tr class='foot'><td></td><td>Range</td>";
                $.each(sobj.totalRangList, function (i1, obj1) {
                    tv += "<td>" + mathUtils.round(obj1.value, digit) + "</td>";
                });
                tv += "</tr></tbody></table>";
                itemBody.html(tv);
            },
            initSummaryAnovaTable: function () {
                data.grrSummaryAnovaDS = [];
                var tb = components.tbl_grr_anova;
                tb.dataTable({
                    "sDom": "rt",
                    "processing": true,
                    "ordering": false,
                    "paging": true,
                    "lengthChange": false,
                    "searching": true,
                    "bFilter": false,
                    "autoWidth": true,
                    "data": function () {
                        return data.grrSummaryAnovaDS;
                    },
                    "language": appConst.table_language()
                });
            },
            initSummarySourceTable: function () {
                data.grrSummarySourceDS = [];
                var tb = components.tbl_grr_source;
                tb.dataTable({
                    "sDom": "rt",
                    "processing": true,
                    "ordering": false,
                    // "paging": true,
                    "lengthChange": false,
                    "searching": true,
                    "bFilter": false,
                    "autoWidth": true,
                    "data": function () {
                        return data.grrSummarySourceDS;
                    },
                    "language": appConst.table_language(),
                    "columnDefs": [{
                        "targets": [4],
                        "render": function (d, type, full) {
                            if (d != "-") {
                                return mathUtils.round(d, 2) + "%";
                            }
                            return d;
                        }
                    }, {
                        "targets": [5],
                        "render": function (d, type, full) {
                            if (d != "-") {
                                return mathUtils.round(d, 2) + "%";
                            }
                            return d;
                        }
                    }, {
                        "targets": [6],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            if (row == 4) {
                                if (stringUtils.isNotBlank(cellData) && cellData != '-') {
                                    var result = checkSummaryLevel(rowData[7]);
                                    $(td).addClass(result.value);
                                }
                            }
                        },
                        "render": function (d, type, full) {
                            if (d != "-") {
                                return mathUtils.round(d, 2) + "%";
                            }
                            return d;
                        }
                    }]
                });
            },
            loadSummaryAnovaTable: function () {
                var dsArray = new Array();
                var d = data.grrItemDetailDS.grrAnovaDtoList;
                var digit = data.custom.digit;
                $(d).each(function (i, obj) {
                    var arr = new Array();
                    arr.push(obj.keyValue);
                    arr.push(mathUtils.round(obj.dfValue, digit));
                    arr.push(mathUtils.round(obj.ssValue, digit));
                    arr.push(mathUtils.round(obj.msValue, digit));
                    arr.push(mathUtils.round(obj.fValue, digit));
                    arr.push(mathUtils.round(obj.probFValue, digit));
                    dsArray.push(arr);
                });
                data.grrSummaryAnovaDS = dsArray;
                components.tbl_grr_anova.dataTable().api().clear().rows.add(data.grrSummaryAnovaDS).draw();
            },
            loadSummarySourceTable: function () {
                var dsArray = new Array();
                var d = data.grrItemDetailDS.grrSourceDtoList;
                var digit = data.custom.digit;
                $(d).each(function (i, obj) {
                    var arr = new Array();
                    arr.push(obj.keyValue);
                    arr.push(mathUtils.round(obj.variation, digit));
                    arr.push(mathUtils.round(obj.sigma, digit));
                    arr.push(mathUtils.round(obj.xSigma, digit));
                    arr.push(obj.contribution);
                    arr.push(obj.totalVariation);
                    arr.push(obj.tolerance);
                    arr.push(obj.result);
                    dsArray.push(arr);
                });
                data.grrSummarySourceDS = dsArray;
                components.tbl_grr_source.dataTable().api().clear().rows.add(data.grrSummarySourceDS).draw();
            },
            toggleAnovaAndSourceSubPanel: function (opt) {
                var btns = $('#' + components.btn_grr_collapseBtn1.attr('id') + ', #' + components.btn_grr_collapseBtn2.attr('id') + ', #' + components.btn_grr_collapseBtn3.attr('id'));
                var theOthers = btns.parent().nextAll("div, ul, table, hr");

                var img = btns.find('span > i');
                if (opt == 'show') {
                    theOthers.show();
                    img.removeClass('fa-angle-left');
                    img.addClass('fa-angle-down');
                } else {
                    theOthers.hide();
                    img.removeClass('fa-angle-down');
                    img.addClass('fa-angle-left');
                }
            },

            //Charts
            loadChartData: function (callback) {
                var param = that.getSearchParams();
                param.search_itemName = data.currentItemName;

                grrM.findChartData(param, function (d) {
                    data.grrChartDS = d;
                    if ($.isFunction(callback)) {
                        callback();
                    }
                });
            },
            buildCharts: function () {
                that.buildXBarChart();
                that.buildRChart();
                that.buildResByOperatorChart();
                that.buildResByPartChart();
                that.buildComponentsChart();
                that.buildGrrPlotChart();
            },
            buildXBarChart: function () {
                components.cht_grr_xbar.empty().html('');
                var chart = d3.select('#' + components.cht_grr_xbar.attr('id'));

                var operatorValue = parseInt(data.grrSettingDS.operatorValue);
                var partValue = parseInt(data.grrSettingDS.partValue);
                var trialValue = parseInt(data.grrSettingDS.trialValue);

                var lstemp = data.grrChartDS.xbarValue.slice(-3);
                var lsValue = [];
                if (mathUtils.isNumeric(lstemp[0])) {
                    lsValue.push({value: lstemp[0], text: 'UCL', color: appConst.colors.red});
                }
                if (mathUtils.isNumeric(lstemp[1])) {
                    lsValue.push({value: lstemp[1], text: 'C', color: appConst.colors.warning});
                }
                if (mathUtils.isNumeric(lstemp[2])) {
                    lsValue.push({value: lstemp[2], text: 'LCL', color: appConst.colors.red});
                }

                var yValue = data.grrChartDS.xbarValue.slice(0, -3);
                var xValue = d3.range(1, yValue.length + 1);
                // for (var i = 0; i < operatorValue; i++) {
                //     for (var k = 0; k < partValue; k++) {
                //         xValue.push(i + 1);
                //     }
                // }
                var areaLineValue = [];
                for (var i = 1; i < operatorValue; i++) {
                    areaLineValue.push(i * partValue + 0.5);
                }

                var barData = d3.zip(xValue, yValue);

                var heightValue = 250;
                var margin = {top: 5, right: 30, bottom: 30, left: 60};
                var width = components.cht_grr_xbar.width() - margin.left - margin.right;
                var height = heightValue - margin.top - margin.bottom;

                var xMax = d3.max(xValue);
                // var xMin = d3.min(xValue);
                var yMax = d3.max(data.grrChartDS.xbarValue);
                var yMin = d3.min(data.grrChartDS.xbarValue);

                var x = d3.scale.linear()
                    .domain([0, xMax + 1])
                    .range([0, width]);

                var yStep = (yMax - yMin) * 0.1;
                var y = d3.scale.linear()
                    .domain([yMin - yStep, yMax + yStep])
                    .range([height, 0]);

                var currentOp = 0;
                var xAxis = d3.svg.axis()
                    .scale(x)
                    .tickValues(xValue)
                    // .ticks(operatorValue)
                    .orient("bottom")
                    .tickSize(0, -height)
                    .tickPadding(8)
                    // .tickFormat(d3.format("d"))
                    .tickFormat(function (dd) {
                        if (dd != 0) {
                            if ((dd % partValue) == (partValue - 1)) {
                                currentOp++;
                                return "Operator" + d3.format("d")(currentOp);
                            } else {
                                return "";
                            }
                        }
                        return dd;
                    });

                var yAxis = d3.svg.axis()
                    .scale(y)
                    .orient("left")
                    .tickFormat(d3.format("C"))
                    .ticks(5)
                    .tickSize(-width, -width)
                    .tickPadding(8);

                var svg = chart
                    .append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .attr("height", height + margin.top + margin.bottom);

                var container = svg.append('g')
                    .attr("class", "focus")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                container.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis);

                container.append("g")
                    .attr("class", "y axis")
                    .call(yAxis);

                //area line
                var areaLine = container.selectAll('.arealine')
                    .data(areaLineValue)
                    .enter().append("line")
                    .attr('class', 'arealine')
                    .attr('x1', function (d) {
                        return x(d);
                    })
                    .attr('x2', function (d) {
                        return x(d);
                    })
                    .attr('y1', function (d) {
                        return 0;
                    })
                    .attr('y2', function (d) {
                        return height;
                    })
                    .attr('stroke', function (d) {
                        return appConst.colors.green;
                    })
                    .attr('stroke-width', '1')
                    .attr("stroke-dasharray", function (d) {
                        return "3";
                    })
                    .style("opacity", "1");

                var lsLine = container.selectAll('.line')
                    .data(lsValue)
                    .enter().append("line")
                    .attr('class', 'line')
                    .attr('x1', function (d) {
                        return 0;
                    })
                    .attr('x2', function (d) {
                        return width;
                    })
                    .attr('y1', function (d) {
                        return y(d.value);
                    })
                    .attr('y2', function (d) {
                        return y(d.value);
                    })
                    .attr('stroke', function (d) {
                        return d.color;
                    })
                    .attr('stroke-width', '1')
                    // .attr("stroke-dasharray", function (d) {
                    //     return "3";
                    // })
                    .style("opacity", "1");

                var lsLinetext = container.selectAll('.lsLinetext')
                    .data(lsValue)
                    .enter().append('text')
                    .attr('class', 'lsLinetext')
                    .text(function (d) {
                        return d.text + "=" + d.value;
                    })
                    .attr("text-anchor", "middle")
                    .attr("x", function (d, i) {
                        return width / 2;
                    })
                    .attr("y", function (d) {
                        return y(d.value) - 3;
                    })
                    .attr("font-size", "12px")
                    .attr("fill", function (d) {
                        return d.color;
                    })
                    .style("opacity", "1");

                container.append("path")
                    .datum(barData)
                    .attr("class", "curveline")
                    .attr("style", "fill: none; stroke: " + appConst.colors.blue + ";stroke-width: 1px;")
                    .attr("d", d3.svg.line()
                        .x(function (dd, i) {
                            return x(dd[0]);
                        })
                        .y(function (dd) {
                            return y(dd[1]);
                        }));

                var tip = d3.tip().attr('class', 'd3-tip')
                    .offset([-10, 0])
                    .html(function (dd, i) {
                        return "<span>" + dd[1] + "</span>";
                    });

                var circles = container.append('g').call(tip).attr('class', 'bcg');
                circles
                    .selectAll('.bcircle')
                    .data(barData)
                    .enter().append("circle")
                    .attr("class", 'bcircle')
                    .attr("fill", appConst.colors.blue)
                    .attr("r", 2.5)
                    .attr("cx", function (dd, i) {

                        return x(dd[0]);
                    })
                    .attr("cy", function (dd) {
                        return y(dd[1]);
                    })
                    .on('mouseover', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 5);
                        tip.show(dd, i);
                    })
                    .on('mouseout', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 2.5);
                        tip.hide();
                    });


            },
            buildRChart: function () {
                components.cht_grr_r.empty().html('');
                var chart = d3.select('#' + components.cht_grr_r.attr('id'));

                var operatorValue = parseInt(data.grrSettingDS.operatorValue);
                var partValue = parseInt(data.grrSettingDS.partValue);
                var trialValue = parseInt(data.grrSettingDS.trialValue);

                var lstemp = data.grrChartDS.rValue.slice(-3);
                var lsValue = [];
                if (mathUtils.isNumeric(lstemp[0])) {
                    lsValue.push({value: lstemp[0], text: 'UCL', color: appConst.colors.red});
                }
                if (mathUtils.isNumeric(lstemp[1])) {
                    lsValue.push({value: lstemp[1], text: 'C', color: appConst.colors.warning});
                }
                if (mathUtils.isNumeric(lstemp[2])) {
                    lsValue.push({value: lstemp[2], text: 'LCL', color: appConst.colors.red});
                }

                var yValue = data.grrChartDS.rValue.slice(0, -3);
                // var yValue = data.grrChartDS.rValue;
                var xValue = d3.range(1, yValue.length + 1);
                // for (var i = 0; i < operatorValue; i++) {
                //     for (var k = 0; k < partValue; k++) {
                //         xValue.push(i + 1);
                //     }
                // }
                var lineValue = [];
                for (var i = 1; i < operatorValue; i++) {
                    lineValue.push(i * partValue + 0.5);
                }

                var barData = d3.zip(xValue, yValue);

                var heightValue = 250;
                var margin = {top: 5, right: 30, bottom: 30, left: 60};
                var width = components.cht_grr_xbar.width() - margin.left - margin.right;
                var height = heightValue - margin.top - margin.bottom;

                var xMax = d3.max(xValue);
                // var xMin = d3.min(xValue);
                var yMax = d3.max(data.grrChartDS.rValue);
                var yMin = d3.min(data.grrChartDS.rValue);

                var x = d3.scale.linear()
                    .domain([0, xMax + 1])
                    .range([0, width]);
                var yStep = (yMax - yMin) * 0.1;
                var y = d3.scale.linear()
                    .domain([yMin - yStep, yMax + yStep])
                    .range([height, 0]);
                var currentOp = 0;
                var xAxis = d3.svg.axis()
                    .scale(x)
                    .tickValues(xValue)
                    // .ticks(operatorValue)
                    .orient("bottom")
                    .tickSize(0, -height)
                    .tickPadding(8)
                    // .tickFormat(d3.format("d"))
                    .tickFormat(function (dd) {
                        if (dd != 0) {
                            if ((dd % partValue) == (partValue - 1)) {
                                currentOp++;
                                return "Operator" + d3.format("d")(currentOp);
                            } else {
                                return "";
                            }
                        }
                        return dd;
                    });

                var yAxis = d3.svg.axis()
                    .scale(y)
                    .orient("left")
                    .tickFormat(d3.format("C"))
                    .ticks(5)
                    .tickSize(-width, -width)
                    .tickPadding(8);

                var svg = chart
                    .append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .attr("height", height + margin.top + margin.bottom);

                var container = svg.append('g')
                    .attr("class", "focus")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                container.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis);

                container.append("g")
                    .attr("class", "y axis")
                    .call(yAxis);

                var line = container.selectAll('.arealine')
                    .data(lineValue)
                    .enter().append("line")
                    .attr('class', 'arealine')
                    .attr('x1', function (d) {
                        return x(d);
                    })
                    .attr('x2', function (d) {
                        return x(d);
                    })
                    .attr('y1', function (d) {
                        return 0;
                    })
                    .attr('y2', function (d) {
                        return height;
                    })
                    .attr('stroke', function (d) {
                        return appConst.colors.green;
                    })
                    .attr('stroke-width', '1')
                    .attr("stroke-dasharray", function (d) {
                        return "3";
                    })
                    .style("opacity", "1");

                var lsLine = container.selectAll('.line')
                    .data(lsValue)
                    .enter().append("line")
                    .attr('class', 'line')
                    .attr('x1', function (d) {
                        return 0;
                    })
                    .attr('x2', function (d) {
                        return width;
                    })
                    .attr('y1', function (d) {
                        return y(d.value);
                    })
                    .attr('y2', function (d) {
                        return y(d.value);
                    })
                    .attr('stroke', function (d) {
                        return d.color;
                    })
                    .attr('stroke-width', '1')
                    // .attr("stroke-dasharray", function (d) {
                    //     return "3";
                    // })
                    .style("opacity", "1");
                var lsLinetext = container.selectAll('.lsLinetext')
                    .data(lsValue)
                    .enter().append('text')
                    .attr('class', 'lsLinetext')
                    .text(function (d) {
                        return d.text + "=" + d.value;
                    })
                    .attr("text-anchor", "middle")
                    .attr("x", function (d, i) {
                        return width / 2;
                    })
                    .attr("y", function (d) {
                        return y(d.value) - 3;
                    })
                    .attr("font-size", "12px")
                    .attr("fill", function (d) {
                        return d.color;
                    })
                    .style("opacity", "1");

                container.append("path")
                    .datum(barData)
                    .attr("class", "curveline")
                    .attr("style", "fill: none;stroke: " + appConst.colors.blue + ";stroke-width: 1px;")
                    .attr("d", d3.svg.line()
                        .x(function (dd, i) {
                            return x(dd[0]);
                        })
                        .y(function (dd) {
                            return y(dd[1]);
                        }));

                var tip = d3.tip().attr('class', 'd3-tip')
                    .offset([-10, 0])
                    .html(function (dd, i) {
                        return "<span>" + dd[1] + "</span>";
                    });
                var circles = container.append('g').call(tip).attr('class', 'bcg');
                circles
                    .selectAll('.bcircle')
                    .data(barData)
                    .enter().append("circle")
                    .attr("class", 'bcircle')
                    .attr("fill", appConst.colors.blue)
                    .attr("r", 2.5)
                    .attr("cx", function (dd, i) {

                        return x(dd[0]);
                    })
                    .attr("cy", function (dd) {
                        return y(dd[1]);
                    })
                    .on('mouseover', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 5);
                        tip.show(dd, i);
                    })
                    .on('mouseout', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 2.5);
                        tip.hide();
                    });


            },
            buildResByOperatorChart: function () {
                var digit = data.custom.digit;
                components.cht_grr_resbyoperator.empty().html('');
                var chart = d3.select('#' + components.cht_grr_resbyoperator.attr('id'));

                var operatorValue = parseInt(data.grrSettingDS.operatorValue);
                var partValue = parseInt(data.grrSettingDS.partValue);
                var trialValue = parseInt(data.grrSettingDS.trialValue);

                var items = data.grrChartDS.resByOperatorValue;

                var avgValue = [];
                var yValue = [];
                var xValue = d3.range(1, operatorValue + 1);
                var dataValue = [];
                var i = 0;
                $.each(items, function (i1, obj1) {
                    var v = Number(mathUtils.round(obj1, digit));
                    if (i1 % (partValue * trialValue + 1) == (partValue * trialValue)) {
                        avgValue.push([i + 1, v]);
                        i++;
                        return;
                    }
                    yValue.push(v);
                    dataValue.push([i + 1, v]);
                });

                var yMax = Number(d3.max(yValue));
                var yMin = Number(d3.min(yValue));
                var yStep = Number(mathUtils.round(Math.abs(yMax - yMin) * 0.1, digit));

                var heightValue = 250;
                var margin = {top: 5, right: 30, bottom: 30, left: 60};
                var width = components.cht_grr_xbar.width() - margin.left - margin.right;
                var height = heightValue - margin.top - margin.bottom;

                var x = d3.scale.linear()
                    .domain([0, operatorValue + 1])
                    .range([0, width]);

                var y = d3.scale.linear()
                    .domain([yMin - yStep, yMax + yStep])
                    .range([height, 0]);

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .tickValues(xValue)
                    // .ticks(operatorValue)
                    .orient("bottom")
                    .tickSize(0, -height)
                    .tickPadding(8)
                    // .tickFormat(d3.format("d"))
                    .tickFormat(function (dd) {
                        if (dd != 0) {
                            return "Operator" + dd;
                        }
                        return dd;
                    });

                var yAxis = d3.svg.axis()
                    .scale(y)
                    .orient("left")
                    .tickFormat(d3.format("C"))
                    // .tickFormat(d3.format("0,.4f"))
                    .ticks(5)
                    .tickSize(-width, -width)
                    .tickPadding(8);

                var svg = chart
                    .append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .attr("height", height + margin.top + margin.bottom)
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                var container = svg.append('g')
                    .attr("class", "focus")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                container.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis);

                container.append("g")
                    .attr("class", "y axis")
                    .call(yAxis);

                var tip = d3.tip().attr('class', 'd3-tip')
                    .offset([-10, 0])
                    .html(function (dd, i) {
                        return "<span>" + dd[1] + "</span>";
                    });
                var circles = container.append('g').call(tip).attr('class', 'bcg');

                circles
                    .selectAll('.bcircle')
                    .data(dataValue)
                    .enter().append("circle")
                    .attr("class", 'bcircle')
                    .attr("fill", appConst.colors.blue)
                    .attr("r", 2.5)
                    .attr("cx", function (dd, i) {
                        return x(dd[0]);
                    })
                    .attr("cy", function (dd) {
                        return y(dd[1]);
                    })
                    .on('mouseover', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 5);
                        tip.show(dd, i);
                    })
                    .on('mouseout', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 2.5);
                        tip.hide();
                    });

                circles
                    .selectAll('.avgcircle')
                    .data(avgValue)
                    .enter().append("circle")
                    .attr("class", 'avgcircle')
                    .attr("fill", appConst.colors.red)
                    .attr("r", 3)
                    .attr("cx", function (dd, i) {
                        return x(dd[0]);
                    })
                    .attr("cy", function (dd) {
                        return y(dd[1]);
                    })
                    .on('mouseover', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 5);
                        tip.show(dd, i);
                    })
                    .on('mouseout', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 3);
                        tip.hide();
                    });


                container.append("path")
                    .datum(avgValue)
                    .attr("class", "curveline")
                    .attr("style", "fill: none;stroke: brown;stroke-width: 1px;")
                    .attr("d", d3.svg.line()
                        .x(function (dd, i) {
                            return x(dd[0]);
                        })
                        .y(function (dd) {
                            return y(dd[1]);
                        }));


            },
            buildResByPartChart: function () {
                var digit = data.custom.digit;
                components.cht_grr_resbypart.empty().html('');
                var chart = d3.select('#' + components.cht_grr_resbypart.attr('id'));

                var operatorValue = parseInt(data.grrSettingDS.operatorValue);
                var partValue = parseInt(data.grrSettingDS.partValue);
                var trialValue = parseInt(data.grrSettingDS.trialValue);

                var items = data.grrChartDS.resByPartValue;

                var avgValue = [];

                var yValue = [];
                var xValue = d3.range(1, partValue + 1);
                var dataValue = [];
                var i = 0;
                $.each(items, function (i1, obj1) {
                    var v = Number(mathUtils.round(obj1, digit));
                    if (i1 % (operatorValue * trialValue + 1) == (operatorValue * trialValue)) {
                        avgValue.push([i + 1, v]);
                        i++;
                        return;
                    }
                    yValue.push(v);
                    dataValue.push([i + 1, v]);
                });

                var yMax = Number(d3.max(yValue));
                var yMin = Number(d3.min(yValue));
                var yStep = Number(mathUtils.round(Math.abs(yMax - yMin) * 0.1, digit));
                var heightValue = 250;
                var margin = {top: 5, right: 30, bottom: 30, left: 60};
                var width = components.cht_grr_xbar.width() - margin.left - margin.right;
                var height = heightValue - margin.top - margin.bottom;

                var x = d3.scale.linear()
                    .domain([0, partValue + 1])
                    .range([0, width]);

                var y = d3.scale.linear()
                    .domain([yMin - yStep, yMax + yStep])
                    .range([height, 0]);

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .tickValues(xValue)
                    // .ticks(operatorValue)
                    .orient("bottom")
                    .tickSize(0, -height)
                    .tickPadding(8)
                    // .tickFormat(d3.format("d"))
                    .tickFormat(function (dd) {
                        if (dd != 0) {
                            return "Part" + dd;
                        }
                        return dd;
                    });

                var yAxis = d3.svg.axis()
                    .scale(y)
                    .orient("left")
                    .tickFormat(d3.format("C"))
                    // .tickFormat(d3.format("0,.4f"))
                    .ticks(5)
                    .tickSize(-width, -width)
                    .tickPadding(8);

                var svg = chart
                    .append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .attr("height", height + margin.top + margin.bottom)
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                var container = svg.append('g')
                    .attr("class", "focus")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                container.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis);

                container.append("g")
                    .attr("class", "y axis")
                    .call(yAxis);

                var tip = d3.tip().attr('class', 'd3-tip')
                    .offset([-10, 0])
                    .html(function (dd, i) {
                        return "<span>" + dd[1] + "</span>";
                    });
                var circles = container.append('g').call(tip).attr('class', 'bcg');

                circles
                    .selectAll('.bcircle')
                    .data(dataValue)
                    .enter().append("circle")
                    .attr("class", 'bcircle')
                    .attr("fill", appConst.colors.blue)
                    .attr("r", 2.5)
                    .attr("cx", function (dd, i) {
                        return x(dd[0]);
                    })
                    .attr("cy", function (dd) {
                        return y(dd[1]);
                    })
                    .on('mouseover', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 5);
                        tip.show(dd, i);
                    })
                    .on('mouseout', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 2.5);
                        tip.hide();
                    });

                circles
                    .selectAll('.avgcircle')
                    .data(avgValue)
                    .enter().append("circle")
                    .attr("class", 'avgcircle')
                    .attr("fill", appConst.colors.red)
                    .attr("r", 3)
                    .attr("cx", function (dd, i) {
                        return x(dd[0]);
                    })
                    .attr("cy", function (dd) {
                        return y(dd[1]);
                    })
                    .on('mouseover', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 5);
                        tip.show(dd, i);
                    })
                    .on('mouseout', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 3.5);
                        tip.hide();
                    });


                container.append("path")
                    .datum(avgValue)
                    .attr("class", "curveline")
                    .attr("style", "fill: none;stroke: brown;stroke-width: 1px;")
                    .attr("d", d3.svg.line()
                        .x(function (dd, i) {
                            return x(dd[0]);
                        })
                        .y(function (dd) {
                            return y(dd[1]);
                        }));
            },
            buildComponentsChart: function () {
                components.cht_grr_components.empty().html('');
                var chart = d3.select('#' + components.cht_grr_components.attr('id'));
                var items = data.grrChartDS.componentValue;
                var n = items.length;
                var m = items[0].length;
                var stack = d3.layout.stack();
                var layers = stack(d3.range(n).map(function (d, index) {
                    return items[index].map(function (d, i) {
                        return {x: i, y: items[index][i]};
                    });
                }));
                var yStackMax = d3.max(layers, function (layer) {
                    return d3.max(layer, function (d) {
                        return d.y;
                    });
                });

                var heightValue = 250;
                var margin = {top: 5, right: 120, bottom: 30, left: 60};
                var width = components.cht_grr_components.width() - margin.left - margin.right;
                var height = heightValue - margin.top - margin.bottom;

                var x = d3.scale.ordinal()
                    .domain(d3.range(m))
                    .rangeRoundBands([0, width], .2);

                var y = d3.scale.linear()
                    .domain([0, 1.1 * yStackMax])
                    .range([height, 0]);

                var datax = ["Repeatability", "Reproducibility", "Gage R&R", "Parts"];
                var dataValues = ["%Contribution", "%Variation", "%Tolerance"];

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .tickSize(0, -height)
                    .tickPadding(5)
                    .orient("bottom")
                    .tickFormat(function (dd) {
                        return datax[dd];
                    });

                var yAxis = d3.svg.axis()
                    .scale(y)
                    .orient("left")
                    .tickFormat(function (dd) {
                        return dd + "%";
                    })
                    .ticks(5)
                    .tickSize(-width, -width);

                var svg = chart
                    .append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .attr("height", height + margin.top + margin.bottom)
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                var container = svg.append('g')
                    .attr("class", "focus")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                container.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis);

                container.append("g")
                    .attr("class", "y axis")
                    .call(yAxis);

                var color = [appConst.colors.warning, appConst.colors.blue, appConst.colors.red];
                var layer = container.selectAll(".layer")
                    .data(layers)
                    .enter().append("g")
                    .attr("class", "layer")
                    .style("fill", function (d, i) {
                        return color[i];
                    });

                var rects = layer.selectAll("rect")
                    .data(function (d) {
                        return d;
                    })
                    .enter()
                    .append("rect")
                    .attr("x", function (d, i, j) {
                        return x(d.x) + x.rangeBand() / n * j;
                    })
                    .attr("width", x.rangeBand() / n)
                    .transition()
                    .attr("y", function (d) {
                        if (d.y === "NaN") {
                            return 0;
                        }
                        else {
                            return y(d.y);
                        }
                    })
                    .attr("height", function (d) {
                        if (d.y === "NaN") {
                            return 0;
                        }
                        else {
                            return height - y(d.y);
                        }
                    });

                layer
                    .selectAll("text.bartext")
                    .data(function (d) {
                        return d;
                    })
                    .enter()
                    .append("text")
                    .attr("class", "bartext")
                    .attr("style", "font-size:10px;")
                    .attr("x", function (d, i, j) {
                        return x(d.x) + x.rangeBand() / n * j;
                    })
                    .attr("y", function (d, i) {
                        return (isNaN(y(d.y)) ? y(0) : y(d.y));
                    })
                    .attr("dy", 12)
                    .attr("transform", "translate(5,-15)")
                    .text(function (d, i) {
                        return (isNaN(d.y) ? 0 : mathUtils.round(d.y, 2)) + "%";
                    });


                var labHeight = 50;
                var labelRect = layer.append("rect")
                    .attr("x", function (d) {
                        return width + margin.left - margin.right * 0.4;
                    })
                    .attr("y", function (d, i) {
                        return margin.top * 2 + labHeight * i;
                    })
                    .attr("width", 16)
                    .attr("height", 16);

                var labelText = layer.append("text")
                    .attr("x", function (d) {
                        return width + margin.left - margin.right * 0.25;
                    })
                    .attr("y", function (d, i) {
                        return margin.top * 2 + labHeight * i;
                    })
                    .attr("dy", 12)
                    .attr("style", "font-size:10px")
                    .text(function (d, i) {
                        return dataValues[i];
                    });
            },
            buildGrrPlotChart: function () {
                components.cht_grr_plot.empty().html('');
                var chart = d3.select('#' + components.cht_grr_plot.attr('id'));
                var partValue = parseInt(data.grrSettingDS.partValue);
                var operatorValue = parseInt(data.grrSettingDS.operatorValue);

                var items = data.grrChartDS.aplotValue;
                var heightValue = 250;
                var margin = {top: 5, right: 30, bottom: 30, left: 60};
                var width = components.cht_grr_xbar.width() - margin.left - margin.right;
                var height = heightValue - margin.top - margin.bottom;

                var allData = d3.merge(items);
                var yMax = d3.max(allData);
                var yMin = d3.min(allData);
                var offset = (yMax - yMin) / 10;
                var xValue = d3.range(0, partValue + 1);
                var x = d3.scale.linear()
                    .domain([0, partValue + 1])
                    .range([0, width]);

                var y = d3.scale.linear()
                    .domain([yMin - offset, yMax + offset])
                    .range([height, 0]);
                var xAxis = d3.svg.axis()
                    .scale(x)
                    .tickValues(xValue)
                    //.tickSize(0)
                    .tickPadding(6)
                    .tickSize(0, -height)
                    .tickFormat(function (dd) {
                        if (dd != 0) {
                            return "Part" + dd;
                        }
                        return dd;
                    })
                    .orient("bottom");
                var yAxis = d3.svg.axis()
                    .scale(y)
                    .ticks(5)
                    .tickSize(-width, -width)
                    .tickPadding(8)
                    .orient("left");
                var svg = chart.append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .attr("height", height + margin.top + margin.bottom);

                var container = svg.append('g')
                    .attr("class", "focus")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                container.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis);

                container.append("g")
                    .attr("class", "y axis")
                    .call(yAxis)
                    .append("text")
                    .attr("transform", "rotate(-90)")
                    .attr("y", 6)
                    .attr("dy", ".71em")
                    .style("text-anchor", "end");

                var line = d3.svg.line()
                    .x(function (d, i) {
                        return x(i + 1);
                    })
                    .y(function (d, i) {
                        return y(d);
                    });
                var partItemG = container.selectAll(".partitem")
                    .data(items, function (d, i) {
                        return d;
                    })
                    .enter().append("g")
                    .attr("class", "partitem");
                var color = d3.scale.linear()
                    .domain([0, operatorValue - 1])
                    .range([appConst.colors.blue, appConst.colors.red]);

                partItemG.append("path")
                    .attr("class", "line")
                    .attr("d", function (d) {
                        for (var j = 0; j < d.length; j++) {
                            if (d[j] == "NaN") {
                                d.splice(j, 1);
                            }
                        }
                        return line(d);
                    })
                    .style("stroke", function (d, i) {
                        return color(i);
                    });

                partItemG.append("text")
                    .datum(function (d) {
                        for (var j = 0; j < d.length; j++) {
                            if (d[j] == "NaN") {
                                d.splice(j, 1);
                            }
                        }
                        return d;
                    })
                    .attr("transform", function (d) {
                        return "translate(" + (x(d.length) + 10) + "," + y(d[d.length - 1]) + ")";
                    })
                    .attr("fill", function (d, i) {
                        return color(i);
                    })
                    .attr("x", 3)
                    .attr("dy", ".35em")
                    .attr("style", "font-size:10px")
                    .text(function (d, i) {
                        return "Operator" + (i + 1);
                    });

                var tip = d3.tip().attr('class', 'd3-tip')
                    .offset([-10, 0])
                    .html(function (dd) {
                        return "<span>" + mathUtils.round(dd, data.custom.digit) + "</span>";
                    });
                var cc = -1;
                var circles = partItemG.append('g').call(tip).attr('class', 'bcg');
                circles.selectAll('.circle')
                    .data(function (d, i) {
                        return d;
                    })
                    .enter()
                    .append("circle")
                    .attr("class", 'circle')
                    .attr("fill", function (d, i) {
                        if (i == 0) {
                            cc++;
                        }
                        return color(cc);
                    })
                    .attr("r", 3)
                    .attr("cx", function (dd, i) {
                        return x(i + 1);
                    })
                    .attr("cy", function (dd, i) {
                        return y(dd);
                    })
                    .on('mouseover', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 5);
                        tip.show(dd, i);
                    })
                    .on('mouseout', function (dd, i) {
                        d3.select(this).transition().duration(250).attr('r', 3.5);
                        tip.hide();
                    });
            },

            //View data panel
            initViewDataPanel: function () {
                that.initViewDataSlot();
                that.initViewDataButtons();

                that.initGrrViewDataChoiceModalDialog();
            },

            initViewDataSlot: function () {
                data.grrSummarySlotDS = [];
                components.slt_grr_viewdata_slot.select2({
                    id: function (rs) {
                        return rs.id;
                    },
                    //allowClear: true,
                    data: function () {
                        return {results: data.grrSummarySlotDS};
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.text == null ? '' : d.text + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.text == null ? '' : d.text;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_viewdata_slot.on('change', function (e) {
                    data.currentSelectedGroupKey = $(this).select2('val');
                    data.currentGroupKey = $(this).select2('data').odata;
                    that.loadViewDataTable();
                });
            },
            initViewDataButtons: function () {
                components.btn_grr_viewdata_submit.on('click', function (e) {
                    that.submitViewDataSetting();
                });
            },
            loadViewDataTable: function () {
                var param = that.getSearchParams();
                widgetUtils.toggleWidgetLoading(components.wgt_grrSummary);
                grrM.findGrrTestData(param, function (d) {
                    data.grrViewDataDS = d;
                    that.buildViewDataTable();
                    widgetUtils.toggleWidgetLoading(components.wgt_grrSummary);
                }, function () {
                    widgetUtils.toggleWidgetLoading(components.wgt_grrSummary, "reset");
                });
            },
            cleanViewDataTable: function () {
                var table = '<thead> <tr> <th style="min-width:20px;"></th> <th>Part</th> <th >Operator</th> <th>Part</th></tr> </thead>';
                table += '<tbody> <tr> <td colspan="4" class="text-center" style="padding: 20px 10px !important;">No data available in table</td></tr></tbody>';
                components.tbl_grr_viewdata.empty().html(table);
            },
            buildViewDataTable: function () {
                var digit = data.custom.digit;
                var isSlotModel = data.psGrrDataDS.model == "SLOT" ? true : false;
                var table = '<thead>' +
                    '<tr><th style="min-width:20px;width:20px;"></th>' +
                    '<th style="min-width:20px;width:20px;">' +
                    '</th><th>Part</th><th>Operator</th> <th>Trial</th>';

                var items = data.grrViewDataDS;
                if (items.length == 0) {
                    that.cleanViewDataTable();
                    return false;
                }
                var cells = items[0].colValueDtoList;
                $.each(cells, function (i, obj) {
                    var key = obj.key.length > 10 ? '<span title="' + obj.key + '">' + obj.key.substr(0, 7) + '...</span>' : obj.key;
                    table += "<th>" + key + "</th>";
                });

                table += '</tr></thead><tbody>';
                var classArray = ['warning', 'danger'];
                var classNo = 0;
                var currentPart = "";
                var rowNo = data.grrSettingDS.partValue * data.grrSettingDS.trialValue * data.grrSettingDS.operatorValue;
                var snNo = data.grrSettingDS.trialValue * data.grrSettingDS.operatorValue;

                var currentRow = 0;
                var tempPartName = "";
                $.each(items, function (i, obj) {
                    if (currentPart != obj.part) {
                        currentPart = obj.part;
                        classNo++;

                        if (classNo > 1) {
                            classNo = 0;
                        }
                    }
                    var className = classArray[classNo];
                    var dataType = "NORMAL";
                    if (i >= rowNo) {
                        dataType = "BACKUP";
                        className = "success"
                    }

                    table += '<tr>';
                    if (tempPartName != obj.part) {
                        currentRow = 0;
                        tempPartName = obj.part;
                    }
                    if (obj.check == true) {
                        // if(tempPartName != obj.part) {
                        //     currentRow = 0;
                        //     currentRow = obj.part;
                        // }
                        if (currentRow == 0) {
                            table += '<td><label class="checkbox" style="float:left;"><input type="checkbox" class="partcheck" data-type="' + dataType + '" data-part="' + obj.part + '" name="checkbox-inline" checked><i></i></label></td>';
                        } else {
                            table += '<td></td>';
                        }
                        currentRow++;
                        if (currentRow == snNo) {
                            currentRow = 0;
                        }
                        table += '<td><label class="checkbox"><input type="checkbox" data-code="' + obj.id + '" data-type="' + dataType + '" data-part="' + obj.part + '" data-opt="' + obj.operator + '" name="checkbox-inline" checked><i></i></label></td>';
                    } else {
                        if (currentRow == 0) {
                            table += '<td><label class="checkbox" style="float:left;"><input type="checkbox" class="partcheck" data-type="' + dataType + '" data-part="' + obj.part + '" name="checkbox-inline"><i></i></label></td>';
                        } else {
                            table += '<td></td>';
                        }
                        currentRow++;
                        if (currentRow == snNo) {
                            currentRow = 0;
                        }
                        table += '<td><label class="checkbox"><input type="checkbox" data-code="' + obj.id + '" data-type="' + dataType + '" data-part="' + obj.part + '" data-opt="' + obj.operator + '" name="checkbox-inline"><i></i></label></td>';
                    }

                    var pa = obj.part.length > 10 ? '<span title="' + obj.part + '">' + obj.part.substr(0, 7) + '...</span>' : obj.part;
                    var op = obj.operator.length > 10 ? '<span title="' + obj.operator + '">' + obj.operator.substr(0, 7) + '...</span>' : obj.operator;
                    var tri = obj.trial.length > 10 ? '<span title="' + obj.trial + '">' + obj.trial.substr(0, 7) + '...</span>' : obj.trial;

                    table += '<td class="' + className + '">' + pa + '</td><td>' + op + '</td><td>' + tri + '</td>';
                    var c = obj.colValueDtoList;
                    $.each(c, function (i1, obj1) {
                        table += "<td>" + mathUtils.round(obj1.value, digit) + "</td>";
                    });
                    table += '</tr>';
                });

                table += "</tbody>";
                components.tbl_grr_viewdata.empty().html(table);
                components.tbl_grr_viewdata.find('input.partcheck').unbind('click').on('click', function (e) {
                    var dataPart = $(this).attr('data-part');
                    var dataType = $(this).attr('data-type');
                    var checkboxes = $(this).parents('tr').nextAll(':lt(' + (Number(snNo - 1)) + ')').find('input[type="checkbox"][data-type="' + dataType + '"][data-part="' + dataPart + '"]:not(.partcheck)');
                    checkboxes.push($(this).parents('tr').find('input[type="checkbox"]:not(.partcheck)')[0]);

                    if ($(this).is(':checked')) {
                        checkboxes.prop('checked', true);
                    } else {
                        checkboxes.prop('checked', false);
                    }
                });

            },
            submitViewDataSetting: function () {
                var normalIds = [];
                var backupIds = [];

                var normals = components.tbl_grr_viewdata.find('tbody input[type="checkbox"][data-type="NORMAL"]:not(:checked):not(.partcheck)');
                $.each(normals, function (i, obj) {
                    normalIds.push($(this).attr('data-code'));
                });

                var backups = components.tbl_grr_viewdata.find('tbody input[type="checkbox"][data-type="BACKUP"]:checked:not(.partcheck)');
                $.each(backups, function (i, obj) {
                    backupIds.push($(this).attr('data-code'));
                });


                //validate ids which to save.
                var validate = that.validateViewData();
                if (validate == false) {
                    msgBox.show({
                        content: "Please check the numbers of backup records matching the removed.",
                        type: "warning"
                    });
                    return;
                }


                var param = that.getSearchParams();
                param.search_includeIds = JSON.stringify(backupIds);
                param.search_excludeIds = JSON.stringify(normalIds);
                grrM.saveGrrTestData(param, function (d) {
                    that.loadViewDataTable();
                });

            },
            validateViewData: function () {
                var normalsObj = components.tbl_grr_viewdata.find('tbody input[type="checkbox"][data-type="NORMAL"]:checked:not(.partcheck)');
                var backupsObj = components.tbl_grr_viewdata.find('tbody input[type="checkbox"][data-type="BACKUP"]:checked:not(.partcheck)');
                var normals = [];
                $.each(normalsObj, function (i, obj) {
                    normals.push({part: $(obj).attr('data-part'), operator: $(obj).attr('data-opt')});
                });
                var backups = [];
                $.each(backupsObj, function (i, obj) {
                    backups.push({part: $(obj).attr('data-part'), operator: $(obj).attr('data-opt')});
                });

                var rowNo = data.grrSettingDS.partValue * data.grrSettingDS.trialValue * data.grrSettingDS.operatorValue;

                if ((normals.length + backups.length) != rowNo) {
                    return false;
                }

                var allChecked = normals.concat(backups);

                var partArr = getNos(allChecked);
                var partNo = data.grrSettingDS.trialValue * data.grrSettingDS.operatorValue;

                if (partArr.length != data.grrSettingDS.partValue) {
                    return false;
                }

                var isPass = true;

                $.each(partArr, function (i, obj) {
                    var no = obj[1];
                    if (no != partNo) {
                        isPass = false;
                        return false;
                    }
                });

                var isSlotModel = data.psGrrDataDS.model == "SLOT" ? true : false;

                if (isSlotModel) {
                    var operatorDim = [];
                    $.each(allChecked, function (i, obj) {
                        operatorDim.push({part: obj.part + "_" + obj.operator});
                    });
                    var operatorArr = getNos(operatorDim);
                    $.each(operatorArr, function (i, obj) {
                        var no = obj[1];
                        if (no != Number(data.grrSettingDS.trialValue)) {
                            isPass = false;
                            return false;
                        }
                    });
                }

                function getNos(arrayObj) {
                    var temp = "";
                    var count = 0;
                    var arrNew = new Array();
                    var arrPartN = new Array();
                    for (var i = 0; i < arrayObj.length; i++) {
                        if (temp != arrayObj[i].part && ($.inArray(arrayObj[i].part, arrPartN) == -1)) {
                            temp = arrayObj[i].part;

                            for (var j = 0; j < arrayObj.length; j++) {
                                if (arrayObj[i].part == arrayObj[j].part) {
                                    count++;
                                }
                            }
                            arrPartN.push(temp);
                            arrNew.push([temp, count]);
                            count = 0;
                        }
                    }
                    return arrNew;
                }

                return isPass;
            },

            //Import modal dialog
            initGrrImportModalDialog: function () {
                var wizard = components.wzd_grr_import;
                wizard.wizard('selectedItem', {
                    step: 1
                });

                components.slt_grr_import_project.select2({
                    id: function (rs) {
                        return rs.id;
                    },
                    allowClear: true,
                    data: function () {
                        return {results: data.projectDS, text: 'name'};
                    },
                    formatResult: function (data) {
                        var itemFmt = "<span>" + data.name == null ? '' : data.name + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (data) {
                        return data.name == null ? '' : data.name;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_import_project.on('change', function (e) {
                    that.cleanGrrImportDialogForm();
                    var param = {
                        search_projectId: $(this).val()
                    };
                    that.loadPsGrrData(param, function (d) {
                        data.importPsGrrDataDS = d;
                        data.currentImportProjectModel = d.model;

                        var wstep = d.model == "NORMAL" ? 1 : 2;
                        wizard.wizard('selectedItem', {
                            step: wstep
                        });
                        components.txt_grr_import_projectId.val(param.search_projectId);
                        components.txt_grr_import_projectId2.val(param.search_projectId);
                        that.resetGrrImportDialogForm();
                    });
                    that.loadPSA(param, function (d) {
                        data.importPsaDs = [];

                        var arr = new Array();
                        $.each(d, function (i, obj) {
                            if (obj.name != "startTime"
                                && obj.name != "stopTime"
                                && obj.name != "isPass"
                                && obj.name != "failingTestItems") {
                                arr.push(obj);
                            }
                        });
                        data.importPsaDs = arr;
                    });
                });

                //init data source select
                components.slt_grr_import_type.select2({
                    id: function (rs) {
                        return rs.id;
                    },
                    allowClear: true,
                    data: function () {
                        return {
                            results: [{id: "file", text: "1 CVS File"}
                                // {id: "mfile", text: "More CVS File, 1 for each Operator"}
                            ]
                        };
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.text == null ? '' : d.text + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.text == null ? '' : d.text;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_import_type.select2('val', 'file');
                //init data source select
                components.slt_grr_import_type2.select2({
                    id: function (rs) {
                        return rs.id;
                    },
                    allowClear: true,
                    data: function () {
                        return {
                            results: [{id: "file", text: "1 CSV File"}
                                // {id: "mfile", text: "More CSV File, 1 for each Operator"}
                            ]
                        };
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.text == null ? '' : d.text + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.text == null ? '' : d.text;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_import_type2.select2('val', 'file');
                //init first change select
                components.slt_grr_import_firstChange.select2({
                    id: function (rs) {
                        return rs.id;
                    },
                    allowClear: true,
                    data: function () {
                        return {
                            results: [{id: "OPERATOR", text: "Appraisers"},
                                {id: "TRIAL", text: "Trial"}]
                        };
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.text == null ? '' : d.text + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.text == null ? '' : d.text;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_import_firstChange.select2('val', 'TRIAL');

                // init group select
                components.slt_grr_import_bind_group_f.select2({
                    id: function (rs) {
                        return rs.name;
                    },
                    allowClear: true,
                    data: function () {
                        return {results: data.importPsaDs};
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.value == null ? '' : d.value + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.value == null ? '' : d.value;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_import_bind_group_s.select2({
                    id: function (rs) {
                        return rs.name;
                    },
                    allowClear: false,
                    data: function () {
                        return {results: data.importPsaDs};
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.value == null ? '' : d.value + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.value == null ? '' : d.value;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_import_bind_attr_part.select2({
                    id: function (rs) {
                        return rs.name;
                    },
                    allowClear: true,
                    data: function () {
                        return {results: data.importPsaDs};
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.value == null ? '' : d.value + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.value == null ? '' : d.value;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });

                components.slt_grr_import_bind_group_f.on('change', function (e) {
                    var arr = $.extend({}, {}, data.importPsaDs);
                    $.each(arr, function (i, obj) {
                        // if()
                    });

                    components.slt_grr_import_bind_group_f_isdefualt.val($(this).select2('data').isDefault);
                });
                components.slt_grr_import_bind_group_s.on('change', function (e) {
                    components.slt_grr_import_bind_group_s_isdefualt.val($(this).select2('data').isDefault);
                });
                components.slt_grr_import_bind_attr_part.on('change', function (e) {
                    components.slt_grr_import_bind_attr_part_isdefualt.val($(this).select2('data').isDefault);
                });

                // init group select
                components.slt_grr_import_bind_group_f2.select2({
                    id: function (rs) {
                        return rs.name;
                    },
                    allowClear: true,
                    data: function () {
                        return {results: data.importPsaDs};
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.value == null ? '' : d.value + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.value == null ? '' : d.value;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_import_bind_group_s2.select2({
                    id: function (rs) {
                        return rs.name;
                    },
                    allowClear: false,
                    data: function () {
                        return {results: data.importPsaDs};
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.value == null ? '' : d.value + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.value == null ? '' : d.value;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_import_bind_attr_part2.select2({
                    id: function (rs) {
                        return rs.name;
                    },
                    allowClear: true,
                    data: function () {
                        return {results: data.importPsaDs};
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.value == null ? '' : d.value + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.value == null ? '' : d.value;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_import_bind_attr_operator.select2({
                    id: function (rs) {
                        return rs.name;
                    },
                    allowClear: true,
                    data: function () {
                        return {results: data.importPsaDs};
                    },
                    formatResult: function (d) {
                        var itemFmt = "<span>" + d.value == null ? '' : d.value + "</span>";
                        return itemFmt;
                    },
                    formatSelection: function (d) {
                        return d.value == null ? '' : d.value;
                    },
                    formatMatches: function () {
                    },
                    formatNoMatches: function () {
                        return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                    },
                    escapeMarkup: function (m) {
                        return m;
                    }
                });
                components.slt_grr_import_bind_group_f2.on('change', function (e) {
                    components.slt_grr_import_bind_group_f2_isdefualt.val($(this).select2('data').isDefault);
                });
                components.slt_grr_import_bind_group_s2.on('change', function (e) {
                    components.slt_grr_import_bind_group_s2_isdefualt.val($(this).select2('data').isDefault);
                });
                components.slt_grr_import_bind_attr_part2.on('change', function (e) {
                    components.slt_grr_import_bind_attr_part2_isdefualt.val($(this).select2('data').isDefault);
                });
                components.slt_grr_import_bind_attr_operator.on('change', function (e) {
                    components.slt_grr_import_bind_attr_operator_isdefualt.val($(this).select2('data').isDefault);
                });


                components.dlg_grr_import.on('show.bs.modal', function (e) {
                    that.cleanSocket();
                    that.initSocket();
                    that.cleanGrrImportDialogForm();
                    that.cleanGrrImportDialogProcess();

                    data.projectDS = searchbar.getProjectDS();
                    var projectId = searchbar.getCurrentChoiceProjectId();
                    components.slt_grr_import_project.select2("val", searchbar.getCurrentChoiceProjectId());
                    if (!stringUtils.isBlank(projectId)) {
                        var param = {
                            search_projectId: projectId
                        };
                        that.loadPsGrrData(param, function (d) {
                            data.importPsGrrDataDS = d;
                            data.currentImportProjectModel = d.model;

                            var wstep = d.model == "NORMAL" ? 1 : 2;
                            wizard.wizard('selectedItem', {
                                step: wstep
                            });
                            components.txt_grr_import_projectId.val(param.search_projectId);
                            components.txt_grr_import_projectId2.val(param.search_projectId);
                            that.resetGrrImportDialogForm();
                        });
                        that.loadPSA(param, function (d) {
                            data.importPsaDs = [];

                            var arr = new Array();
                            $.each(d, function (i, obj) {
                                if (obj.name != "startTime"
                                    && obj.name != "stopTime"
                                    && obj.name != "isPass"
                                    && obj.name != "failingTestItems") {
                                    arr.push(obj);
                                }
                            });
                            data.importPsaDs = arr;
                        });
                    } else {
                        that.resetGrrImportDialogForm();
                    }


                });
                components.dlg_grr_import.on('hide.bs.modal', function (e) {
                    that.cleanSocket();
                    if (components.slt_grr_import_project.select2('val') == searchbar.getCurrentChoiceProjectId()) {
                        searchbar.reloadStation();
                        searchbar.doSearch();
                    }
                });
                components.btn_grr_import_submit.on('click', function (e) {
                    // wizard.wizard('selectedItem', {
                    //     step: 2
                    // });
                    // wizard.wizard('next');
                    if (that.doImportGrrData() == false) {
                        return;
                    }

                    wizard.wizard('selectedItem', {
                        step: 3
                    });
                    components.slt_grr_import_project.prop('disabled', true);
                    // $(this).button('loading');
                    $(this).hide();
                    components.btn_grr_import_gobackTo1.show();
                    that.cleanGrrImportDialogProcess();
                    timedCount(0);

                    function timedCount(c) {
                        var time = dateUtils.second_to_date(c);
                        components.spn_grr_import_time.html(time);

                        var timeout = setTimeout(function () {
                            timedCount(c + 1);
                        }, 1000);
                        var obj = {timeout: timeout};
                        appLocalStorage.setLocal(data.search_timeout_key_grr, JSON.stringify(obj));
                    }
                });
                components.btn_grr_import_gobackTo1.on('click', function (e) {
                    // wizard.wizard('previous');
                    var wstep = data.currentImportProjectModel == "NORMAL" ? 1 : 2;
                    wizard.wizard('selectedItem', {
                        step: wstep
                    });

                    that.cleanSocket();
                    that.initSocket();

                    $(this).hide();
                    components.slt_grr_import_project.prop('disabled', false);
                    that.cleanGrrImportDialogProcess();
                    components.btn_grr_import_submit.show();
                });
            },
            loadPSA: function (param, callback) {
                var p = {
                    id: param.search_projectId
                };
                grrM.findPSA(p, function (d) {
                    if ($.isFunction(callback)) {
                        callback(d);
                    }
                });
            },
            cleanGrrImportDialogProcess: function () {
                components.spn_grr_import_processbar.removeClass("progress-bar-danger").removeClass("progress-bar-success");
                components.spn_grr_import_processbar.css('width', '0%');
                components.spn_grr_import_processbar.attr("aria-valuenow", 0);
                components.spn_grr_import_logArea.empty();
                components.spn_grr_import_status.empty();
            },
            cleanGrrImportDialogForm: function () {
                components.txt_grr_import_partValue.val('');
                components.txt_grr_import_operatorValue.val('');
                components.txt_grr_import_trialValue.val('');

                components.txt_grr_import_partValue2.val('');
                components.txt_grr_import_operatorValue2.val('');
                components.txt_grr_import_trialValue2.val('');
                components.txt_grr_import_grrName.val('');
                components.txt_grr_import_grrName2.val('');

                components.fle_grr_import_file.val('');
                components.fle_grr_import_file2.val('');
                components.slt_grr_import_slotGroup.val('');

                components.slt_grr_import_bind_group_f.select2('val', '');
                components.slt_grr_import_bind_group_s.select2('val', '');
                components.slt_grr_import_bind_attr_part.select2('val', '');

                components.slt_grr_import_bind_group_f2.select2('val', '');
                components.slt_grr_import_bind_group_s2.select2('val', '');
                components.slt_grr_import_bind_attr_part2.select2('val', '');
                components.slt_grr_import_bind_attr_operator.select2('val', '');
            },
            resetGrrImportDialogForm: function () {
                var wstep = data.currentImportProjectModel == "NORMAL" ? 1 : 2;
                components.slt_grr_import_project.prop('disabled', false);
                if (wstep == 1) {
                    //init import value
                    var defaultMV = ["", "", ""];
                    if (data.importPsGrrDataDS.defaultModelValue != null) {
                        defaultMV = JSON.parse(data.importPsGrrDataDS.defaultModelValue);
                    }

                    // part-operator-trial
                    components.txt_grr_import_partValue.val(defaultMV[0]);
                    components.txt_grr_import_operatorValue.val(defaultMV[1]);
                    components.txt_grr_import_trialValue.val(defaultMV[2]);

                    components.btn_grr_import_submit.show();
                    components.btn_grr_import_gobackTo1.hide();
                    components.slt_grr_import_type.select2('val', 'file');
                    components.slt_grr_import_firstChange.select2('val', 'TRIAL');
                    components.wzd_grr_import.wizard('selectedItem', {
                        step: wstep
                    });

                } else {
                    //init import value
                    var defaultMV = ["", "", ""];
                    if (data.importPsGrrDataDS.defaultModelValue != null) {
                        defaultMV = JSON.parse(data.importPsGrrDataDS.defaultModelValue);
                    }
                    // part-operator-trial
                    components.txt_grr_import_partValue2.val(defaultMV[0]);
                    components.txt_grr_import_operatorValue2.val(defaultMV[1]);
                    components.txt_grr_import_trialValue2.val(defaultMV[2]);
                    components.txt_grr_import_operatorValue2.next('span').html('<strong>Slot</strong>');

                    components.btn_grr_import_submit.show();
                    components.btn_grr_import_gobackTo1.hide();
                    components.slt_grr_import_type2.select2('val', 'file');

                    components.slt_grr_import_slotGroup.val('');
                    components.txt_grr_import_grrName2.val('');
                    components.wzd_grr_import.wizard('selectedItem', {
                        step: wstep
                    });
                }

                var now = new Date();
                var nowGrrName = "GRR_" + now.Format('yyyyMMddHHmmss');
                components.txt_grr_import_grrName.val(nowGrrName);
                components.txt_grr_import_grrName2.val(nowGrrName);
                components.fle_grr_import_file.val("");
            },
            doImportGrrData: function () {
                var projectId = components.slt_grr_import_project.select2('val');
                components.alt_grr_import_msgbar.html('').hide();
                if (stringUtils.isBlank(projectId)) {
                    components.alt_grr_import_msgbar.html('Please choice a project.').show();
                    return false;
                }
                var wstep = data.currentImportProjectModel == "NORMAL" ? 1 : 2;
                var fileForm = $('#frm_grr_import');
                var fileForm2 = $('#frm_grr_import2');
                fileForm.attr("action", 'analysis/grr/import');
                fileForm2.attr("action", 'analysis/grr/import');
                var isHasPermission = true;
                if (wstep == 1) {
                    jQuery.validator.addMethod("keyGrrName", function (value, element) {
                        var that = this;
                        var isExsit = true;
                        var isComplete = false;
                        $.ajax({
                            type: "POST",
                            url: "analysis/grr/checkGrrName",
                            dataType: 'json',
                            async: false,
                            data: {
                                search_grrName: $('#txt_grr_import_grrName').val().trim(),
                                search_projectId: $('#txt_grr_import_projectId').val().trim()
                            },
                            success: function (data) {
                                if (data.code == 0) {
                                    isHasPermission = false;
                                    msgBox.errorBox(data.message);
                                } else {
                                    isExsit = data.body;
                                }
                                isComplete = true;
                            },
                            error: function (e) {
                                if (e.status == 401) {
                                    msgBox.sessionFailureBox();
                                }
                                if (e.status == 500) {
                                    msgBox.serverFailureBox();
                                }
                                if (e.status == 404) {
                                    msgBox.pathFailureBox();
                                }
                                isHasPermission = false;
                                isComplete = true;
                            }
                        });
                        if (isComplete) {
                            return isExsit;
                        }
                    }, $.i18n.prop('EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS', 'GRR name'));
                    var $import_validate = components.frm_grr_import.validate({
                        rules: {
                            file: {
                                required: true,
                                keyFile: true
                            },
                            operatorValue: {
                                required: true,
                                digits: true
                                // positiveinteger: true
                            },
                            trialValue: {
                                required: true,
                                digits: true
                            },
                            partValue: {
                                required: true,
                                digits: true
                            },
                            grrName: {
                                required: true,
                                keyGrrName: true
                            }
                        },
                        messages: {
                            operatorValue: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', "Appraisers")
                            },
                            trialValue: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', "Trials")
                            },
                            partValue: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', "Parts")
                            },
                            grrName: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', "GRR Name")
                                //remote: "GRR name is already in system."
                            }
                        },
                        errorPlacement: function (error, element) {
                            error.insertAfter(element.parent());
                        }
                    });
                    var isPass = $import_validate.form();
                    if (isPass == false) {
                        $import_validate.focusInvalid();
                        return false;
                    }

                    if (!isHasPermission) {
                        return false;
                    }

                    var groupKey1 = components.slt_grr_import_bind_group_f.select2('val');
                    var groupKey2 = components.slt_grr_import_bind_group_s.select2('val');
                    var attrPart = components.slt_grr_import_bind_attr_part.select2('val');
                    if (stringUtils.isBlank(groupKey1) || stringUtils.isBlank(attrPart)) {
                        components.alt_grr_import_msgbar.html('Please select the group and dimension.').show();
                        return false;
                    }
                    if (groupKey1 == groupKey2 || groupKey1 == attrPart || groupKey2 == attrPart) {
                        components.alt_grr_import_msgbar.html('The groups could not be same with the dimension.').show();
                        return false;
                    }
                    fileForm.submit();

                } else {
                    isHasPermission = true;
                    jQuery.validator.addMethod("keyGrrName2", function (value, element) {
                        var that = this;
                        var isExsit = true;
                        var isComplete = false;
                        $.ajax({
                            type: "POST",
                            url: "analysis/grr/checkGrrName",
                            dataType: 'json',
                            async: false,
                            data: {
                                search_grrName: $('#txt_grr_import_grrName2').val().trim(),
                                search_projectId: $('#txt_grr_import_projectId2').val().trim()
                            },
                            success: function (data) {
                                if (data.code == 0) {
                                    isHasPermission = false;
                                    msgBox.errorBox(data.message);
                                } else {
                                    isExsit = data.body;
                                }
                                isComplete = true;
                            },
                            error: function (e) {
                                if (e.status == 401) {
                                    msgBox.sessionFailureBox();
                                }
                                if (e.status == 500) {
                                    msgBox.serverFailureBox();
                                }
                                if (e.status == 404) {
                                    msgBox.pathFailureBox();
                                }
                                isHasPermission = false;
                                isComplete = true;
                            }
                        });
                        if (isComplete) {
                            return isExsit;
                        }
                    }, $.i18n.prop('EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS', 'GRR name'));

                    $.validator.addMethod("slotGroup", function (value, element) {
                        var reg = /^([\S,]+)[;]+$/i;
                        if (reg.test(value) == false) {
                            return false;
                        }

                        var slotGroupValue = value;
                        var slotGroups = slotGroupValue.split(';');
                        slotGroups.splice(slotGroups.length - 1, 1);

                        if (slotGroups.length > 1) {
                            var optValue = components.txt_grr_import_operatorValue2.val();
                            var groupValided = true;
                            $.each(slotGroups, function (i, obj) {
                                var optArr = obj.split(',');
                                if (optArr.length != optValue) {
                                    // components.slt_grr_import_slotGroup.removeClass('state-error','state-success').addClass('state-error');
                                    // console.log($import_validate2.errorsFor('slotGroup'));
                                    groupValided = false;
                                    return false;
                                }
                            });
                            if (groupValided == false) {
                                return false;
                            }
                        }

                        return true;
                    }, "Invalidate Value");

                    var $import_validate2 = components.frm_grr_import2.validate({
                        rules: {
                            file: {
                                required: true,
                                keyFile: true
                            },
                            operatorValue: {
                                required: true,
                                digits: true
                                // positiveinteger: true
                            },
                            trialValue: {
                                required: true,
                                digits: true
                            },
                            partValue: {
                                required: true,
                                digits: true
                            },
                            grrName: {
                                required: true,
                                keyGrrName2: true
                                /*remote: {
                                 type: "POST",
                                 url: "analysis/grr/checkGrrName",
                                 dataType: 'json',
                                 async: false,
                                 data: {
                                 search_grrName: function () {
                                 return components.txt_grr_import_grrName2.val().trim();
                                 },
                                 search_projectId: data.searchFields.search_projectId
                                 }
                                 }*/
                            },
                            slotGroup: {
                                required: true
                                // slotGroup: true
                            }
                        },
                        messages: {
                            file: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', "File")
                            },
                            operatorValue: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', "Appraisers")
                            },
                            trialValue: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', "Trials")
                            },
                            partValue: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', "Parts")
                            },
                            grrName: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', "GRR Name")
                                //remote: "GRR name is already in system."
                            }
                        },
                        errorPlacement: function (error, element) {
                            error.insertAfter(element.parent());
                        }
                    });


                    var isPass = $import_validate2.form();
                    if (isPass == false) {
                        $import_validate2.focusInvalid();
                        return false;
                    }

                    if (!isHasPermission) {
                        return false;
                    }

                    //validate slot format
                    var slotGroup = components.slt_grr_import_slotGroup.val();
                    var groups = slotGroup.split(';');
                    if(groups == null) {
                        components.alt_grr_import_msgbar.html('Please check the test strategy and the operator number.').show();
                        return false;
                    }
                    var operatorNum = Number(components.txt_grr_import_operatorValue2.val());

                    isPass = true;
                    for (var i = 0; i < groups.length; i++) {
                        if(groups[i] == "") {
                            continue;
                        }
                        var opts = groups[i].split(',');
                        if(opts == null) {
                            isPass = false;
                            break;
                        }
                        if(opts.length != operatorNum) {
                            isPass = false;
                            break;
                        }
                    }
                    if (isPass == false) {
                        components.alt_grr_import_msgbar.html('Please check the test strategy format and ensure it be match with the operator number.').show();
                        return false;
                    }

                    var groupKey1 = components.slt_grr_import_bind_group_f2.select2('val');
                    var groupKey2 = components.slt_grr_import_bind_group_s2.select2('val');
                    var attrPart = components.slt_grr_import_bind_attr_part2.select2('val');
                    var attrOperator = components.slt_grr_import_bind_attr_operator.select2('val');
                    if (stringUtils.isBlank(groupKey1) || stringUtils.isBlank(attrPart) || stringUtils.isBlank(attrOperator)) {
                        components.alt_grr_import_msgbar.html('Please select the group and dimension.').show();
                        return false;
                    }
                    if ($.inArray(groupKey1, [groupKey2, attrPart, attrOperator]) != -1 || $.inArray(groupKey2, [groupKey1, attrPart, attrOperator]) != -1
                        || $.inArray(attrPart, [groupKey1, groupKey2, attrOperator]) != -1 || $.inArray(attrOperator, [groupKey1, groupKey2, attrPart]) != -1) {
                        components.alt_grr_import_msgbar.html('The groups could not be same with the dimension.').show();
                        return false;
                    }

                    fileForm2.submit();

                }
                return true;
            },
            initSocket: function () {
                var soltkey = Math.floor(Math.random(10) * 1000000);
                components.txt_grr_import_soltkey.val(soltkey);
                components.txt_grr_import_soltkey2.val(soltkey);
                var ws = socketBiz.initImport(soltkey, that.socketCallback);
                data.ws.sockjs = ws.sockjs;
                data.ws.stomp = ws.stomp;
            },
            cleanSocket: function () {
                if (data.ws.stomp != null) {
                    data.ws.stomp.disconnect(function () {
                        data.ws.sockjs = null;
                        data.ws.stomp = null;
                        var queryParameter = appLocalStorage.getLocal(data.search_timeout_key_grr);
                        if (queryParameter != null) {
                            queryParameter = JSON.parse(queryParameter);
                            var timeout = queryParameter.timeout;
                            clearTimeout(timeout);
                        }
                    });
                }
            },
            socketCallback: function (pdata) {
                if (pdata.target == "GRR") {
                    var userId = global.getUserId();
                    socketBiz.receivedProcess(pdata, {
                        processbar: $("#spn_grr_import_processbar"),
                        pstatus: $('#spn_grr_import_status'),
                        poperator: $('#spn_grr_import_operator'),
                        plog: $('#spn_grr_import_logArea'),
                        psubmit: $('#btn_grr_import_submit'),
                        ptimeoutkey: appConst.searchKey.search_dataImport_timeout_key + "grr." + userId
                    });
                }
            },

            //Choice modal dialog
            initGrrViewDataChoiceModalDialog: function () {
                data.grrChoiceTestItemDS = [];
                var tb = components.tbl_grr_choice_testitem;
                tb.dataTable({
                    "sDom": "t<'dt-toolbar-footer'<'col-xs-12 col-sm-12'p>>",
                    "processing": true,
                    "ordering": false,
                    "paging": true,
                    "lengthChange": false,
                    "searching": true,
                    "bFilter": false,
                    "autoWidth": true,
                    "pageLength": global.getPageSize(),
                    "data": function () {
                        return data.grrChoiceTestItemDS;
                    },
                    "language": appConst.table_language(),
                    "columnDefs": [
                        {
                            "targets": [0],
                            "render": function (d, type, full) {
                                if (full[2] == true) {
                                    return '<label class="checkbox"><input type="checkbox" data-code="' + full[1] + '" name="checkbox-inline" checked><i></i></label>';
                                }
                                else {
                                    return '<label class="checkbox"><input type="checkbox" data-code="' + full[1] + '" name="checkbox-inline"><i></i></label>';
                                }
                            }
                        },
                        {
                            "targets": [2],
                            "visible": false
                        }
                    ]
                });

                components.tbl_grr_choice_testitem.DataTable().on('draw.dt', function () {
                    tb.find('tbody').find('input[type="checkbox"][name="checkbox-inline"]').unbind('click').on('click', function () {
                        var checked = $(this).is(':checked');
                        var itemName = $(this).attr('data-code');
                        var checkAll = true;

                        $.each(data.grrChoiceTestItemDS, function (i, obj) {
                            if (itemName == obj[1]) {
                                obj[2] = checked;
                            }
                            if (obj[2] == false) {
                                checkAll = false;
                            }
                        });
                        if (checkAll) {
                            components.ckb_grr_choice_testitem_topAll.prop("checked", "checked");
                        } else {
                            components.ckb_grr_choice_testitem_topAll.prop("checked", "");
                        }
                    });
                });

                components.dlg_grr_choice.on('show.bs.modal', function (e) {
                    data.grrChoiceTestItemDS = [];
                    $('input[name="rdo_grr_choice_checked"][value="ALL"]').prop('checked', true);
                    tb.dataTable().api().column(2).search('').draw();

                    that.loadViewDataChoiceTestItemTable(function (d) {

                        tb.dataTable().api().clear().rows.add(data.grrChoiceTestItemDS).draw();
                    });
                });

                $('input[name="rdo_grr_choice_checked"]').on('click', function () {
                    var type = $(this).val();
                    if (type == 'ALL') {
                        if (tb.dataTable().api().column(2).data().indexOf(false) != -1) {
                            components.ckb_grr_choice_testitem_topAll.prop('checked', false);
                        } else {
                            components.ckb_grr_choice_testitem_topAll.prop('checked', true);
                        }
                        tb.dataTable().api().clear().rows.add(data.grrChoiceTestItemDS).column(2).search('').draw();
                    } else if (type == 'CHECK') {
                        components.ckb_grr_choice_testitem_topAll.prop('checked', true);
                        tb.dataTable().api().clear().rows.add(data.grrChoiceTestItemDS).column(2).search('true').draw();
                    } else if (type == 'UNCHECK') {
                        components.ckb_grr_choice_testitem_topAll.prop('checked', false);
                        tb.dataTable().api().clear().rows.add(data.grrChoiceTestItemDS).column(2).search('false').draw();
                    }
                });

                components.ckb_grr_choice_testitem_topAll.on('click', function () {

                    // console.log($('input[name="rdo_grr_choice_checked"]:checked'));
                    var checkType = $('input[name="rdo_grr_choice_checked"]:checked').val();
                    var selected = $(this).is(':checked');

                    var currentCheckData = tb.dataTable().api().column(2).search('true').data();
                    if (checkType == 'ALL') {
                        $.each(data.grrChoiceTestItemDS, function (i, obj) {
                            obj[2] = selected;
                        });
                        tb.dataTable().api().column(2).search('').clear().rows.add(data.grrChoiceTestItemDS).draw();
                    } else if (checkType == 'CHECK') {
                        $.each(data.grrChoiceTestItemDS, function (i, obj) {
                            if (currentCheckData[i] == true) {
                                obj[2] = selected;
                            }
                        });
                        tb.dataTable().api().clear().rows.add(data.grrChoiceTestItemDS).column(2).search('true').draw();
                    } else if (checkType == 'UNCHECK') {
                        $.each(data.grrChoiceTestItemDS, function (i, obj) {
                            if (currentCheckData[i] == false) {
                                obj[2] = selected;
                            }
                        });
                        tb.dataTable().api().clear().rows.add(data.grrChoiceTestItemDS).column(2).search('false').draw();
                    }
                });

                //export submit click event
                components.btn_grr_choice_submit.click(function () {
                    var itemNames = [];
                    $.each(data.grrChoiceTestItemDS, function (i, obj) {
                        if (obj[2] == true) {
                            itemNames.push(obj[1]);
                        }
                    });

                    if (itemNames.length == 0) {
                        msgBox.show({
                            content: "Please choice a test item.",
                            type: "warning"
                        });
                        return;
                    }
                    var param = that.getSearchParams();
                    param.search_itemNames = JSON.stringify(itemNames);

                    grrM.saveChoiceTestItem(param, function () {
                        that.loadViewDataTable();
                    });

                    components.dlg_grr_choice.modal('toggle');
                });
            },
            loadViewDataChoiceTestItemTable: function (callback) {
                var param = that.getSearchParams();
                grrM.getChoiceTestItem(param, function (d) {
                    // data.grrChoiceTestItemDS = d;
                    var dsArray = new Array();
                    $(d).each(function (i, obj) {
                        var arr = new Array();
                        arr.push(null);
                        arr.push(obj.key);
                        arr.push(obj.value);
                        dsArray.push(arr);
                    });
                    data.grrChoiceTestItemDS = dsArray;
                    if ($.isFunction(callback)) {
                        callback(d);
                    }
                });
            },

            //Export modal dialog
            initGrrExportModalDialog: function () {
                components.tbl_grr_export_testItem.DataTable({
                    "sDom": "t<'dt-toolbar-footer'<'col-xs-12 col-sm-12'p>>",
                    "processing": true,
                    "ordering": false,
                    "paging": true,
                    "lengthChange": false,
                    "searching": true,
                    "bFilter": false,
                    "autoWidth": true,
                    "pageLength": global.getPageSize(),
                    "data": function () {
                        return data.grrExportTestItemDS;
                    },
                    "columnDefs": [
                        {
                            "targets": [0],
                            "render": function (d, type, full) {
                                if (full[2]) {
                                    return "<label class='checkbox'><input type='checkbox' class='grr_ckb_item' id=ckb_" + full[1] + "  value=" + full[1] + " checked='checked'><i></i></label>";
                                }
                                return "<label class='checkbox'><input type='checkbox' class='grr_ckb_item' id=ckb_" + full[1] + "  value=" + full[1] + "><i></i></label>";
                            }
                        }
                    ]
                });

                components.tbl_grr_export_testItem.DataTable().on('draw.dt', function () {
                    var dt = $(this).dataTable();
                    dt.find('tbody').find('input[type="checkbox"][class="grr_ckb_item"]').unbind('click').on('click', function () {
                        var checked = $(this).is(':checked');
                        var itemName = $(this).val();
                        var checkAll = true;

                        $.each(data.grrExportTestItemDS, function (i, obj) {
                            if (itemName == obj[1]) {
                                obj[2] = checked;
                            }
                            if (obj[2] == false) {
                                checkAll = false;
                            }
                        });

                        if (checkAll) {
                            components.ckb_grr_export_allCheck.prop("checked", "checked");
                        } else {
                            components.ckb_grr_export_allCheck.prop("checked", "");
                        }
                    });
                });

                components.dlg_grr_export.on('show.bs.modal', function (e) {
                    components.ckb_grr_export_allCheck.prop('checked', true);
                    that.loadExportTestItemTable(function (d) {
                        components.tbl_grr_export_testItem.dataTable().api().clear().rows.add(data.grrExportTestItemDS).draw();

                    });
                });

                //export all checkbox click event
                components.ckb_grr_export_allCheck.click(function () {
                    var checkAll = $(this).is(':checked');
                    $.each(data.grrExportTestItemDS, function (i, obj) {
                        obj[2] = checkAll;
                    });
                    components.tbl_grr_export_testItem.dataTable().api().clear().rows.add(data.grrExportTestItemDS).draw();
                });

                //export submit click event
                components.btn_grr_export_submit.click(function () {
                    //get choosen radio value
                    var exportType = components.radio_grr_export_type.filter(':checked').val();

                    var itemNames = [];
                    $.each(data.grrExportTestItemDS, function (i, obj) {
                        if (obj[2] == true) {
                            itemNames.push(obj[1]);
                        }
                    });

                    if (itemNames.length == 0) {
                        msgBox.show({
                            content: "Please choice a test item.",
                            type: "warning"
                        });
                        return;
                    }

                    var param = that.getSearchParams();
                    param.search_exportItemNames = JSON.stringify(itemNames);
                    param.search_projectName = data.searchFields.search_projectName;

                    if (exportType == "onlyResult") {
                        grrM.exportGrrDataSummary(param, function (d) {
                            msgBox.show({
                                content: "<span id='grr_export_message' style='font-size:15px;'><i class='fa fa-refresh fa-spin animated'></i> Exporting ... You can track the exporting progress in <a href='#exportfile/all' > Export History</a></span>",
                                type: "success",
                                timeout: 0
                            });
                        });
                    } else if (exportType == "resultData") {
                        grrM.exportGrrDataAll(param, function () {
                            msgBox.show({
                                content: "<span id='grr_export_message' style='font-size:15px;'><i class='fa fa-refresh fa-spin animated'></i> Exporting ... You can track the exporting progress in <a href='#exportfile/all' > Export History</a></span>",
                                type: "success",
                                timeout: 0
                            });
                        });
                    }

                    components.dlg_grr_export.modal('toggle');
                });
            },
            loadExportTestItemTable: function (callback) {
                data.grrExportTestItemDS = [];
                if (data.grrChoiceTestItemDS == null || data.grrChoiceTestItemDS.length == 0) {
                    that.loadViewDataChoiceTestItemTable(function (d) {
                        var dsArray = new Array();
                        $.each(data.grrChoiceTestItemDS, function (i, obj) {
                            if (obj[2] == true) {
                                dsArray.push($.extend({}, obj));
                            }
                        });
                        data.grrExportTestItemDS = dsArray;
                        if ($.isFunction(callback)) {
                            callback(data.grrExportTestItemDS);
                        }
                    });
                } else {
                    var dsArray = new Array();
                    $.each(data.grrChoiceTestItemDS, function (i, obj) {
                        if (obj[2] == true) {
                            dsArray.push($.extend({}, obj));
                        }
                    });
                    data.grrExportTestItemDS = dsArray;
                    if ($.isFunction(callback)) {
                        callback(data.grrExportTestItemDS);
                    }
                }
            },

            resetAllPanel: function () {

                components.btn_grr_deleteGrrItem.prop("disabled", true);

                components.btn_grr_import.prop("disabled", false);
                components.btn_grr_export.prop("disabled", true);

                components.btn_grr_viewdata_submit.prop("disabled", true);
                components.btn_grr_viewdata_choiceitem.prop("disabled", true);


                components.slt_grr_summary_slot.select2('val', '');
                components.slt_grr_viewdata_slot.select2('val', '');
            },

            getSearchParams: function () {
                var searchParam = {
                    "search_projectId": data.searchFields.search_projectId,
                    "search_grrName": data.currentGrrName
                };

                var arr = new Array();
                arr.push(data.currentGroupKey);
                searchParam.search_analysisKeys = JSON.stringify(arr);
                return searchParam;
            }
        }
    }
)
;